<html>
<head>
    <meta charset="utf-8"/>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>

<title>Spring+SpringMVC+MyBatis学习 | 絷缘的博客</title>

<link rel="shortcut icon" href="https://zydnc.gitee.io/favicon.ico?v=1732378515642">

<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://zydnc.gitee.io/styles/main.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css">

<script src="https://cdn.jsdelivr.net/npm/@highlightjs/cdn-assets/highlight.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.15.10/languages/dockerfile.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.15.10/languages/dart.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/moment@2.27.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js"></script>
<!-- DEMO JS -->
<!--<script src="media/scripts/index.js"></script>-->



    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.css">
 <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
</head>
<body>
<div class="main gt-bg-theme-color-first">
    <nav class="navbar navbar-expand-lg">
    <div class="navbar-brand">
        <img class="user-avatar" src="/images/avatar.png" alt="头像">
        <div class="site-name gt-c-content-color-first">
            絷缘的博客
        </div>
    </div>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <i class="fas fa-bars gt-c-content-color-first" style="font-size: 18px"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <div class="navbar-nav mr-auto" style="text-align: center">
            
                <div class="nav-item">
                    
                        <a href="/" class="menu gt-a-link">
                            首页
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/archives" class="menu gt-a-link">
                            归档
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/tags" class="menu gt-a-link">
                            标签
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/about" class="menu gt-a-link">
                            关于
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/friends" class="menu gt-a-link">
                            友链
                        </a>
                    
                </div>
            
        </div>
        <div style="text-align: center">
            <form id="gridea-search-form" style="position: relative" data-update="1732378515642" action="/search/index.html">
                <input class="search-input" autocomplete="off" spellcheck="false" name="q" placeholder="搜索文章" />
                <i class="fas fa-search gt-c-content-color-first" style="position: absolute; top: 9px; left: 10px;"></i>
            </form>
        </div>
    </div>
</nav>

    <div class="post-container">
        <div class="post-detail gt-bg-theme-color-second">
            <article class="gt-post-content">
                <h2 class="post-title">
                    Spring+SpringMVC+MyBatis学习
                </h2>
                <div class="post-info">
                    <time class="post-time gt-c-content-color-first">
                        · 2021-04-16 ·
                    </time>
                    
                        <a href="https://zydnc.gitee.io/spring/" class="post-tags">
                            # Spring
                        </a>
                    
                        <a href="https://zydnc.gitee.io/springmvc/" class="post-tags">
                            # SpringMVC
                        </a>
                    
                        <a href="https://zydnc.gitee.io/mybatis/" class="post-tags">
                            # Mybatis
                        </a>
                    
                </div>
                <div class="post-content">
                    <h1 id="ssm">SSM</h1>
<ul>
<li>传统Servlet的不足
<ul>
<li>同一个类型的业务要进行多个Servlet的编写，单个Servlet功能单一</li>
<li>对象管理不方便，每次操作业务，都会产生很多对象</li>
</ul>
</li>
</ul>
<h1 id="java中的主流框架技术">Java中的主流框架技术</h1>
<ul>
<li>Struts</li>
<li>Hibernate</li>
<li>Spring</li>
<li>SpringMVC</li>
<li>SpringBoot</li>
<li>MyBatis</li>
</ul>
<h1 id="学习框架的思路">学习框架的思路</h1>
<ul>
<li>框架的规范</li>
<li>框架的底层实现</li>
</ul>
<h1 id="struts2框架的介绍">Struts2框架的介绍</h1>
<ul>
<li>是一个基于mvc设计思想的web应用框架，它本质就是一个Servlet，在mvc设计思想中，Struts2充当的是一个Controller的角色</li>
</ul>
<h1 id="hibernate框架的介绍">Hibernate框架的介绍</h1>
<ul>
<li>开源的对象关系映射框架（ORM）框架</li>
<li>底层就是对JDBC的封装</li>
</ul>
<h1 id="java企业级开发的演化">Java企业级开发的演化</h1>
<ul>
<li><code>Servlet+JavaBean</code></li>
<li><code>Servlet+JSP+JavaBean</code></li>
<li><code>Struts2+Spring+Hibernate:SSH</code></li>
<li><code>Spring+SpringMVC+MyBatis:SSM</code></li>
<li><code>SpringBoot(Spring全家桶开发)</code></li>
</ul>
<h2 id="一-spring">一、Spring</h2>
<blockquote>
<p><code>Spring</code> 是分层的JavaSE/EE应用 <code>full-stack</code> 轻量级开源框架，以 <code> IoC（Inverse Of Control：反转控制）</code> 和 <code>AOP（Aspect Oriented Programming：面向切面编程）</code> 为内核</p>
<p>提供了展现层 <code>Spring MVC</code> 和持久层 <code>Spring JDBCTemplate</code> 以及业务层事务管理等众多的企业级应用技术，还能整合开源世界众多著名的第三方框架和类库，逐渐成为使用最多的JavaEE企业应用开源框架</p>
<p>官网：https://spring.io/</p>
<p><code>Spring</code> 的核心</p>
<ul>
<li><code>IOC</code>：把对象的创建权交给Spring，让Spring帮我们创建并且管理对象</li>
<li><code>DI</code>：给对象的属性注入值</li>
<li><code>AOP</code>：解决了一些面向对象编程不方便解决的问题</li>
</ul>
<p><code>Spring</code> 的优点</p>
<ul>
<li>方便解耦，简化开发，把对象的创建权全部交给了Spring管理</li>
<li>支持AOP编程</li>
<li>声明式事务</li>
<li>Spring很方便继承各种优秀的框架</li>
<li>Spring还对比较难用的api提供了封装，方便我们使用</li>
</ul>
</blockquote>
<h3 id="1-spring-程序开发步骤">1. Spring 程序开发步骤</h3>
<ul>
<li>导入Spring开发的基本包坐标（Maven依赖）</li>
</ul>
<pre><code class="language-xml">&lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-context --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
    &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<ul>
<li>编写Dao接口和实现类（Bean）</li>
</ul>
<pre><code class="language-java">public interface UserDao {
    public abstract void save();
}

public class UserDaoImpl implements UserDao {
    @Override
    public void save() {
        System.out.println(&quot;save方法&quot;);
    }
}
</code></pre>
<ul>
<li>创建Spring核心配置文件（applicationContext.xml）</li>
<li>在Spring配置文件中配置（bean）</li>
</ul>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;&gt;
    &lt;bean id=&quot;userDao&quot; class=&quot;com.zhiyuan.dao.impl.UserDaoImpl&quot;&gt;&lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<ul>
<li>使用Spring的API获得Bean实例（ new ClassPathXmlApplicationContext(&quot;applicationContext.xml&quot;)）</li>
</ul>
<pre><code class="language-java">public class UserDaoDemo {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext(&quot;applicationContext.xml&quot;);
        UserDao userDao = (UserDao) app.getBean(&quot;userDao&quot;);
        userDao.save();
    }
}
</code></pre>
<h3 id="2-spring-配置文件">2. Spring 配置文件</h3>
<h4 id="1-基本属性">①. 基本属性</h4>
<ul>
<li><code>id</code>：Bean实例在Spring容器的唯一标识</li>
<li><code>class</code>：Bean的全限定名称</li>
</ul>
<h4 id="2-范围配置">②. 范围配置</h4>
<ul>
<li><code>scope</code>：对象的作用范围
<ul>
<li><code>singleton</code>：默认值，单例的</li>
<li><code>prototype</code>：多例的</li>
<li><code>request</code>：Web项目中，Spring创建一个Bean对象，将对象存入到request域中</li>
<li><code>session</code>：Web项目中，Spring创建一个Bean对象，将对象存入session域中</li>
<li><code>global session</code>：Web项目中，应用在Portlet环境，如果没有Portlet环境，那么globalSession相当于session</li>
</ul>
</li>
<li>当scope的取值为singleton时
<ul>
<li>Bean的实例化个数：1个</li>
<li>Bean的实例化时机：当Spring核心配置文件被加载时，实例化配置的Bean实例</li>
<li>Bean的生命周期
<ul>
<li>对象创建：当应用加载，创建容器时，对象就被创建了</li>
<li>对象运行：只要容器在，对象一直活着</li>
<li>对象销毁：当应用卸载，销毁容器时，对象就被销毁了</li>
</ul>
</li>
</ul>
</li>
<li>当scope的取值为prototype时
<ul>
<li>Bean的实例化个数：多个</li>
<li>Bean的实例化时机：当调用getBean()方法时实例化Bean
<ul>
<li>对象创建：当使用对象时，创建新的对象实例</li>
<li>对象运行：只要对象在使用中，就一直活着</li>
<li>对象销毁：当对象长时间不用时，被Java的垃圾回收器回收了</li>
</ul>
</li>
</ul>
</li>
</ul>
<h4 id="3-生命周期配置">③. 生命周期配置</h4>
<ul>
<li><code>init-method</code>：指定类中的初始化方法名称</li>
<li><code>destory-method</code>：指定类中销毁方法名称</li>
</ul>
<h4 id="4-bean实例化三种方式">④. Bean实例化三种方式</h4>
<ul>
<li>
<p>无参构造方法实例化</p>
<ul>
<li>
<pre><code class="language-xml">&lt;bean id=&quot;userDao&quot; class=&quot;com.zhiyuan.dao.impl.UserDaoImpl&quot;&gt;&lt;/bean&gt;
</code></pre>
</li>
</ul>
</li>
<li>
<p>工厂静态方法实例化</p>
<ul>
<li>
<pre><code class="language-xml">&lt;bean id=&quot;userDao&quot; class=&quot;com.zhiyuan.factory.StaticFactory&quot; factory-method=&quot;getUserDao&quot;&gt;&lt;/bean&gt;
</code></pre>
</li>
</ul>
</li>
<li>
<p>工厂实例方法实例化</p>
<ul>
<li>
<pre><code class="language-xml">&lt;bean id=&quot;factory&quot; class=&quot;com.zhiyuan.factory.DynamicFactory&quot;&gt;&lt;/bean&gt;
&lt;bean id=&quot;userDao&quot; factory-bean=&quot;factory&quot; factory-method=&quot;getUserDao&quot;&gt;&lt;/bean&gt;
</code></pre>
</li>
</ul>
</li>
</ul>
<h4 id="5-bean的依赖注入">⑤. Bean的依赖注入</h4>
<ul>
<li>程序最终使用的是UserService，而UserService和UserDao都在Spring容器中，所以可以在Spring容器中，将UserDao设置到UserService的内部，这就叫UserService需要UserDao的依赖注入</li>
<li>依赖注入：Dependency Injection（IOC的具体实现）</li>
</ul>
<h5 id="1-set方法注入">1. set方法注入</h5>
<pre><code class="language-java">public class UserServiceImpl implements UserService {
  private UserDao userDao;
  public void setUserDao(UserDao userDao){
      this.userDao = userDao;
  }
  public void save(){
      userDao.save();
  }
}
</code></pre>
<pre><code class="language-xml">&lt;bean id=&quot;userDao&quot; class=&quot;com.zhiyuan.dao.impl.UserDaoImpl&quot;&gt;&lt;/bean&gt;
&lt;bean id=&quot;userService&quot; class=&quot;com.zhiyuan.service.impl.UserServiceImpl&quot;&gt;
&lt;property name=&quot;userDao&quot; ref=&quot;userDao&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;
</code></pre>
<ul>
<li>
<p>简化set方法注入</p>
<ul>
<li>引入命名空间</li>
</ul>
<pre><code class="language-xml">xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
</code></pre>
<ul>
<li>进行依赖注入</li>
</ul>
<pre><code class="language-xml">&lt;bean id=&quot;userDao&quot; class=&quot;com.zhiyuan.dao.impl.UserDaoImpl&quot;&gt;&lt;/bean&gt;
&lt;bean id=&quot;userService&quot; class=&quot;com.zhiyuan.service.impl.UserServiceImpl&quot; p:userDao-ref=&quot;userDao&quot;&gt;&lt;/bean&gt;
</code></pre>
</li>
</ul>
<h5 id="2-构造方法注入">2. 构造方法注入</h5>
<pre><code class="language-java">public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }
    public UserServiceImpl() {}
    public void save(){
        userDao.save();
    }
}
</code></pre>
<pre><code class="language-xml">&lt;bean id=&quot;userDao&quot; class=&quot;com.zhiyuan.dao.impl.UserDaoImpl&quot;&gt;&lt;/bean&gt;
&lt;bean id=&quot;userService&quot; class=&quot;com.zhiyuan.service.impl.UserServiceImpl&quot;&gt;
    &lt;constructor-arg name=&quot;userDao&quot; ref=&quot;userDao&quot;&gt;&lt;/constructor-arg&gt;
&lt;/bean&gt;
</code></pre>
<h5 id="3-普通数据类型注入">3. 普通数据类型注入</h5>
<pre><code class="language-java">public class UserDaoImpl implements UserDao {
    private String username;
    private int age;
    @Override
    public void save() {
        System.out.println(&quot;save方法&quot;);
        System.out.println(username+&quot;-&quot;+age);
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
</code></pre>
<pre><code class="language-xml">&lt;bean id=&quot;userDao&quot; class=&quot;com.zhiyuan.dao.impl.UserDaoImpl&quot;&gt;
    &lt;property name=&quot;age&quot; value=&quot;69&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;username&quot; value=&quot;张三&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;
</code></pre>
<h5 id="4-集合数据类型注入">4. 集合数据类型注入</h5>
<pre><code class="language-xml">&lt;bean id=&quot;userDao&quot; class=&quot;com.zhiyuan.dao.impl.UserDaoImpl&quot;&gt;
    &lt;property name=&quot;age&quot; value=&quot;69&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;username&quot; value=&quot;张三&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;scoreMap&quot;&gt;
        &lt;map&gt;
            &lt;entry key=&quot;k1&quot; value=&quot;v1&quot;&gt;&lt;/entry&gt;
            &lt;entry key=&quot;k2&quot; value=&quot;v2&quot;&gt;&lt;/entry&gt;
        &lt;/map&gt;
    &lt;/property&gt;
    &lt;property name=&quot;list&quot;&gt;
        &lt;list&gt;
            &lt;value&gt;v1&lt;/value&gt;
            &lt;value&gt;v2&lt;/value&gt;
            &lt;ref bean=&quot;beanName&quot;&gt;&lt;/ref&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;
</code></pre>
<h4 id="6-引入其他配置文件">⑥. 引入其他配置文件</h4>
<ul>
<li>
<p>在实际开发中，Spring的配置内容非常多，这就导致Spring配置文件很繁杂体积很大，所以Spring配置文件支持通过import标签引入外部其他的配置文件</p>
<pre><code class="language-xml">&lt;import resource=&quot;applicationContext-xxx.xml&quot; /&gt;
</code></pre>
</li>
</ul>
<h3 id="3-applicationcontext继承体系">3. ApplicationContext继承体系</h3>
<figure data-type="image" tabindex="1"><img src="http://pic.zyblog.xyz/img/typora/20210201124651.png" alt="img" loading="lazy"></figure>
<h4 id="1-applicationcontext">①. ApplicationContext</h4>
<ul>
<li>
<p>接口类型，代表应用上下文，可以通过其实例获得Spring容器中的Bean对象</p>
</li>
<li>
<p>实现类</p>
<ul>
<li>
<p>ClassPathXmlApplicationContext</p>
<ul>
<li>从类的根路径下加载配置文件（推荐）</li>
</ul>
</li>
<li>
<p>FileSystemXmlApplicationContext</p>
<ul>
<li>从磁盘路径中加载配置文件，配置文件可以在任意位置</li>
</ul>
</li>
<li>
<p>AnnotationConfigApplicationContext</p>
<ul>
<li>当使用注解配置容器对象时，需要使用此类来创建Spring容器，它用来读取注解</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="4-常用-api">4. 常用 API</h3>
<h4 id="1-getbean方法">①. getBean()方法</h4>
<ul>
<li><code>getBean(String name)</code>：获取指定类名称的Bean对象</li>
<li><code>getBean(Class&lt;T&gt; requiredType)</code>：获取指定类类型的Bean对象</li>
</ul>
<h3 id="5-spring配置数据源">5. Spring配置数据源</h3>
<h4 id="1-数据源数据库连接池datasource">①. 数据源（数据库连接池：DataSource）</h4>
<ul>
<li><code>DBCP</code> <code>C3P0</code> <code>Druid</code></li>
</ul>
<h4 id="2-数据库连接池的配置">②. 数据库连接池的配置</h4>
<ul>
<li>导入数据库相关依赖</li>
</ul>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;mysql&lt;/groupId&gt;
    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
    &lt;version&gt;8.0.21&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;com.alibaba&lt;/groupId&gt;
    &lt;artifactId&gt;druid&lt;/artifactId&gt;
    &lt;version&gt;1.2.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;com.mchange&lt;/groupId&gt;
    &lt;artifactId&gt;c3p0&lt;/artifactId&gt;
    &lt;version&gt;0.9.5.5&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
    &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<ul>
<li>Spring配置数据库连接池</li>
</ul>
<pre><code class="language-xml">&lt;bean id=&quot;dataSource&quot; class=&quot;com.mchange.v2.c3p0.ComboPooledDataSource&quot;&gt;
    &lt;property name=&quot;driverClass&quot; value=&quot;com.mysql.cj.jdbc.Driver&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;jdbcUrl&quot; value=&quot;jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;user&quot; value=&quot;root&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;password&quot; value=&quot;123456&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;
&lt;bean id=&quot;dataSource&quot; class=&quot;com.alibaba.druid.pool.DruidDataSource&quot;&gt;
    &lt;property name=&quot;driverClassName&quot; value=&quot;com.mysql.cj.jdbc.Driver&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;username&quot; value=&quot;root&quot;&gt;&lt;/property&gt;
    &lt;property name=&quot;password&quot; value=&quot;123456&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;
</code></pre>
<ul>
<li>代码实现</li>
</ul>
<pre><code class="language-java">public class DataSourceDemo1 {
    public static void main(String[] args) throws Exception {
        // ComboPooledDataSource ds = new ComboPooledDataSource();
        // Connection conn = ds.getConnection();
        // String sql  = &quot;select * from user&quot;;
        // PreparedStatement pstat = conn.prepareStatement(sql);
        // ResultSet rs = pstat.executeQuery();
        // while(rs.next()){
        //     System.out.println(rs.getInt(&quot;id&quot;));
        // }
        // ApplicationContext app = new ClassPathXmlApplicationContext(&quot;applicationContext.xml&quot;);
        // DataSource ds = (DataSource)app.getBean(&quot;dataSource&quot;);
        // Connection conn = ds.getConnection();
        // String sql = &quot;select * from user&quot;;
        // PreparedStatement pstat = conn.prepareStatement(sql);
        // ResultSet rs = pstat.executeQuery();
        // while(rs.next()){
        //     System.out.println(rs.getInt(&quot;id&quot;));
        // }
        // DruidDataSource ds = new DruidDataSource();
        // ds.setDriverClassName(&quot;com.mysql.cj.jdbc.Driver&quot;);
        // ds.setUrl(&quot;jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&quot;);
        // ds.setUsername(&quot;root&quot;);
        // ds.setPassword(&quot;123456&quot;);
        // DruidPooledConnection conn = ds.getConnection();
        // String sql = &quot;select * from user&quot;;
        // PreparedStatement pstat = conn.prepareStatement(sql);
        // ResultSet rs = pstat.executeQuery();
        // while(rs.next()){
        //     System.out.println(rs.getInt(&quot;id&quot;));
        // }
        ApplicationContext app = new ClassPathXmlApplicationContext(&quot;applicationContext.xml&quot;);
        DataSource ds = (DataSource)app.getBean(&quot;dataSource&quot;);
        Connection conn = ds.getConnection();
        String sql = &quot;select * from user&quot;;
        PreparedStatement pstat = conn.prepareStatement(sql);
        ResultSet rs = pstat.executeQuery();
        while(rs.next()){
            System.out.println(rs.getInt(&quot;id&quot;));
        }
    }
}
public class DataSourceDemo1 {
    public static void main(String[] args) throws Exception {
        // ComboPooledDataSource ds = new ComboPooledDataSource();
        // Connection conn = ds.getConnection();
        // String sql  = &quot;select * from user&quot;;
        // PreparedStatement pstat = conn.prepareStatement(sql);
        // ResultSet rs = pstat.executeQuery();
        // while(rs.next()){
        //     System.out.println(rs.getInt(&quot;id&quot;));
        // }
        ApplicationContext app = new ClassPathXmlApplicationContext(&quot;applicationContext.xml&quot;);
        DataSource ds = (DataSource)app.getBean(&quot;dataSource&quot;);
        Connection conn = ds.getConnection();
        String sql = &quot;select * from user&quot;;
        PreparedStatement pstat = conn.prepareStatement(sql);
        ResultSet rs = pstat.executeQuery();
        while(rs.next()){
            System.out.println(rs.getInt(&quot;id&quot;));
        }
    }
}
</code></pre>
<h4 id="3-数据库连接池抽取配置文件">③. 数据库连接池抽取配置文件</h4>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;

    &lt;context:property-placeholder location=&quot;classpath:druid.properties&quot;/&gt;
    &lt;bean id=&quot;dataSource&quot; class=&quot;com.alibaba.druid.pool.DruidDataSource&quot;&gt;
        &lt;property name=&quot;driverClassName&quot;  value=&quot;${driverClassName}&quot;/&gt;
        &lt;property name=&quot;url&quot; value=&quot;${url}&quot;/&gt;
        &lt;property name=&quot;username&quot; value=&quot;${username}&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;${password}&quot;/&gt;
        &lt;property name=&quot;initialSize&quot; value=&quot;${initialSize}&quot;/&gt;
        &lt;property name=&quot;maxActive&quot; value=&quot;${maxActive}&quot;/&gt;
        &lt;property name=&quot;maxWait&quot; value=&quot;${maxWait}&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<pre><code class="language-java">DataSource dataSource = (DataSource)app.getBean(&quot;dataSource&quot;);
try {
    Connection conn = dataSource.getConnection();
    System.out.println(conn);
} catch (SQLException throwables) {
    throwables.printStackTrace();
}
</code></pre>
<blockquote>
<p>这里会产生一个严重错误，产生原因是，在applicationContext.xml中，直接使用<span class="katex"><span class="katex-mathml"><math><semantics><mrow><mrow><mi>u</mi><mi>s</mi><mi>e</mi><mi>r</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mi mathvariant="normal">引</mi><mi mathvariant="normal">入</mi><mi mathvariant="normal">的</mi><mi mathvariant="normal">用</mi><mi mathvariant="normal">户</mi><mi mathvariant="normal">名</mi><mi mathvariant="normal">，</mi><mi mathvariant="normal">并</mi><mi mathvariant="normal">非</mi><mi mathvariant="normal">是</mi><mi mathvariant="normal">我</mi><mi mathvariant="normal">们</mi><mi mathvariant="normal">配</mi><mi mathvariant="normal">置</mi><mi mathvariant="normal">文</mi><mi mathvariant="normal">件</mi><mi mathvariant="normal">中</mi><mi mathvariant="normal">的</mi><mi mathvariant="normal">用</mi><mi mathvariant="normal">户</mi><mi mathvariant="normal">名</mi><mi>u</mi><mi>s</mi><mi>e</mi><mi>r</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mi mathvariant="normal">，</mi><mi mathvariant="normal">排</mi><mi mathvariant="normal">查</mi><mi mathvariant="normal">发</mi><mi mathvariant="normal">现</mi><mi mathvariant="normal">当</mi><mi mathvariant="normal">我</mi><mi mathvariant="normal">们</mi><mi mathvariant="normal">直</mi><mi mathvariant="normal">接</mi><mi mathvariant="normal">给</mi><mi mathvariant="normal">用</mi><mi mathvariant="normal">户</mi><mi mathvariant="normal">名</mi><mi mathvariant="normal">可</mi><mi mathvariant="normal">以</mi><mi mathvariant="normal">正</mi><mi mathvariant="normal">常</mi><mi mathvariant="normal">工</mi><mi mathvariant="normal">作</mi><mi mathvariant="normal">，</mi><mi mathvariant="normal">但</mi><mi mathvariant="normal">是</mi><mi mathvariant="normal">使</mi><mi mathvariant="normal">用</mi></mrow><annotation encoding="application/x-tex">{username}引入的用户名，并非是我们配置文件中的用户名username，排查发现当我们直接给用户名可以正常工作，但是使用</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.43056em;vertical-align:0em;"></span><span class="mord"><span class="mord mathdefault">u</span><span class="mord mathdefault">s</span><span class="mord mathdefault">e</span><span class="mord mathdefault" style="margin-right:0.02778em;">r</span><span class="mord mathdefault">n</span><span class="mord mathdefault">a</span><span class="mord mathdefault">m</span><span class="mord mathdefault">e</span></span><span class="mord cjk_fallback">引</span><span class="mord cjk_fallback">入</span><span class="mord cjk_fallback">的</span><span class="mord cjk_fallback">用</span><span class="mord cjk_fallback">户</span><span class="mord cjk_fallback">名</span><span class="mord cjk_fallback">，</span><span class="mord cjk_fallback">并</span><span class="mord cjk_fallback">非</span><span class="mord cjk_fallback">是</span><span class="mord cjk_fallback">我</span><span class="mord cjk_fallback">们</span><span class="mord cjk_fallback">配</span><span class="mord cjk_fallback">置</span><span class="mord cjk_fallback">文</span><span class="mord cjk_fallback">件</span><span class="mord cjk_fallback">中</span><span class="mord cjk_fallback">的</span><span class="mord cjk_fallback">用</span><span class="mord cjk_fallback">户</span><span class="mord cjk_fallback">名</span><span class="mord mathdefault">u</span><span class="mord mathdefault">s</span><span class="mord mathdefault">e</span><span class="mord mathdefault" style="margin-right:0.02778em;">r</span><span class="mord mathdefault">n</span><span class="mord mathdefault">a</span><span class="mord mathdefault">m</span><span class="mord mathdefault">e</span><span class="mord cjk_fallback">，</span><span class="mord cjk_fallback">排</span><span class="mord cjk_fallback">查</span><span class="mord cjk_fallback">发</span><span class="mord cjk_fallback">现</span><span class="mord cjk_fallback">当</span><span class="mord cjk_fallback">我</span><span class="mord cjk_fallback">们</span><span class="mord cjk_fallback">直</span><span class="mord cjk_fallback">接</span><span class="mord cjk_fallback">给</span><span class="mord cjk_fallback">用</span><span class="mord cjk_fallback">户</span><span class="mord cjk_fallback">名</span><span class="mord cjk_fallback">可</span><span class="mord cjk_fallback">以</span><span class="mord cjk_fallback">正</span><span class="mord cjk_fallback">常</span><span class="mord cjk_fallback">工</span><span class="mord cjk_fallback">作</span><span class="mord cjk_fallback">，</span><span class="mord cjk_fallback">但</span><span class="mord cjk_fallback">是</span><span class="mord cjk_fallback">使</span><span class="mord cjk_fallback">用</span></span></span></span>{}引入变量就会造成错误，所以得出一个结论，我们使用${username}调用配置文件的值时，spring会先从默认系统变量中寻找，找到了直接使用默认的，不会继续寻找配置文件中的，被劫糊了，而系统环境变量与实际的数据库username，而两者编码和内容都不一致，导致连接数据库失败</p>
<p>解决办法，不要在配置文件中适用username属性，虽然druid连接池默认应该是username，但是这里使用spring加载，为了避免spring的混乱，所以还是修改一下druid配置文件中username的名字，改成dbusername或者其他，然后在spring配置文件中引入${dbusername}即可</p>
</blockquote>
<pre><code class="language-properties">driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai
dbusername=root
# 将username改为dbusername
password=123456
initialSize=5
maxActive=10
maxWait=3000
</code></pre>
<h3 id="6-spring注解开发">6. Spring注解开发</h3>
<ul>
<li>好处：类比web3.0之前的web开发（配置文件形式的）和web3.0及以后的web开发（注解形式的）</li>
<li>原因：Spring是轻代码重配置的框架，我们需要写的代码其实并不是很多，配置的文件那才是相当的多，配置繁多，影响开发效率，所以注解开发是一种简化开发的解决方案，注解代替xml配置文件即可以简化配置，又可以提高开发效率，何乐而不为</li>
</ul>
<h4 id="1-spring原始注解">①. Spring原始注解</h4>
<table>
<thead>
<tr>
<th>注解名称</th>
<th>适用范围</th>
<th>注解说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>@Component</code></td>
<td>用在所有类上</td>
<td>实例化JavaBean</td>
</tr>
<tr>
<td><code>@Controller</code></td>
<td>用在<code>web</code>层类上</td>
<td>实例化JavaBean（语义化web层）</td>
</tr>
<tr>
<td><code>@Service</code></td>
<td>用在<code>service</code>层类上</td>
<td>实例化JavaBean（语义化service层）</td>
</tr>
<tr>
<td><code>@Repository</code></td>
<td>用在<code>dao</code>层类上</td>
<td>实例化JavaBean（语义化dao层）</td>
</tr>
<tr>
<td><code>@Autowired</code></td>
<td>用在字段上</td>
<td>根据类型进行依赖注入</td>
</tr>
<tr>
<td><code>@Qualifier</code></td>
<td>结合<code>@Autowired</code>，用在字段上</td>
<td>根据名称进行依赖注入</td>
</tr>
<tr>
<td><code>@Resource</code></td>
<td>等同于<code>@Autowired+@Qualifier</code>，用在字段上</td>
<td>按照名称进行依赖注入</td>
</tr>
<tr>
<td><code>@Value</code></td>
<td>用在字段上，一般用在使用<code>${}</code>引入数据库配置文件相关属性上</td>
<td>注入普通属性值</td>
</tr>
<tr>
<td><code>@Scope</code></td>
<td>用在类上，指定实例化模式是 多例 或 单例，<code>prototype</code> 或 <code>singleton</code></td>
<td>标注JavaBean作用范围</td>
</tr>
<tr>
<td><code>@PostConstruct</code></td>
<td>用在方法上，指定JavaBean对象的初始化方法<code>init-method</code></td>
<td>标注JavaBean的初始化方法</td>
</tr>
<tr>
<td><code>@PreDestory</code></td>
<td>用在方法上，指定JavaBean对象的销毁方法<code>destory-method</code></td>
<td>标注JavaBean的销毁方法</td>
</tr>
</tbody>
</table>
<blockquote>
<p>注意：使用注解开发时，需要在applicationContext.xml中配置组件扫描</p>
<p>作用：指定哪个包及其子包下的JavaBean需要进行扫描，需要扫描的注解对应的类，字段和方法</p>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
  xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
  xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
  xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;
&lt;context:component-scan base-package=&quot;com.zhiyuan&quot;/&gt;
&lt;/beans&gt;
</code></pre>
</blockquote>
<h4 id="2-spring新注解">②. Spring新注解</h4>
<blockquote>
<p>虽然原始注解解决了原来很多问题，但依然有些配置问题无法解决，于是Spring新注解出现了，它采用了一种使用类来描述配置文件的方法来提升我们的工作效率，配置文件烦杂，并不意味着我们不再需要配置文件，所以引入了用类来表示配置文件的解决方案</p>
</blockquote>
<table>
<thead>
<tr>
<th>注解名称</th>
<th>适用范围</th>
<th>注解说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>@Configuration</td>
<td>用在类上</td>
<td>指定当前类为Spring配置类，当创建容器时会从该类上加载注释</td>
</tr>
<tr>
<td>@ComponentScan</td>
<td>用在类上</td>
<td>指定Spring在初始化容器时扫描的包，作用等同于<code>&lt;context:component-scan base-package=&quot;com.zhiyuan&quot;/&gt;</code></td>
</tr>
<tr>
<td>@Bean</td>
<td>用在方法上</td>
<td>标注将该方法的返回值存储到Spring容器中</td>
</tr>
<tr>
<td>@PropertySource</td>
<td></td>
<td>用于加载 <code>.properties</code>配置文件中的配置信息</td>
</tr>
<tr>
<td>@Import</td>
<td></td>
<td>用于导入其他配置类</td>
</tr>
</tbody>
</table>
<blockquote>
<pre><code class="language-java">//标志本类为Spring的核心配置类
@Configuration
//设置组件扫描路径（JavaBean的扫描路径），作用等同于&lt;context:component-scan base-package=&quot;com.zhiyuan&quot;/&gt;
@ComponentScan(&quot;com.zhiyuan&quot;)
//引入配置文件
@PropertySource(&quot;classpath:druid.properties&quot;)
public class DruidConfig {
 @Value(&quot;${driverClassName}&quot;)
 private String driver;
 @Value(&quot;${url}&quot;)
 private String url;
 @Value(&quot;${dbusername}&quot;)
 private String username;
 @Value(&quot;${password}&quot;)
 private String password;
 @Value(&quot;${initialSize}&quot;)
 private int initialSize;
 @Value(&quot;${maxActive}&quot;)
 private int maxActive;
 @Value(&quot;${maxWait}&quot;)
 private int maxWait;
 @Bean(&quot;dataSource&quot;)
 public DataSource getDataSource(){
     Properties pros = new Properties();
     DataSource ds = null;
     try {
         pros.setProperty(&quot;driverClassName&quot;,driver);
         pros.setProperty(&quot;url&quot;,url);
         pros.setProperty(&quot;username&quot;,username);
         pros.setProperty(&quot;password&quot;,password);
         pros.setProperty(&quot;initialSize&quot;,String.valueOf(initialSize));
         pros.setProperty(&quot;maxActive&quot;, String.valueOf(maxActive));
         pros.setProperty(&quot;maxWait&quot;, String.valueOf(maxWait));
         ds = DruidDataSourceFactory.createDataSource(pros);
     } catch (Exception e) {
         e.printStackTrace();
     }
     return ds;
 }
}
</code></pre>
<pre><code class="language-java">//标志本类为Spring的核心配置类
@Configuration
//设置组件扫描路径（JavaBean的扫描路径），作用等同于&lt;context:component-scan base-package=&quot;com.zhiyuan&quot;/&gt;
@ComponentScan(&quot;com.zhiyuan&quot;)
//引入配置文件
@PropertySource(&quot;classpath:druid.properties&quot;)
//加入其它配置文件，作用等同于&lt;import resource=&quot;applicationContext-xxx.xml&quot; /&gt;
@Import(DruidConfig.class)
public class SpringConfiguration {

}
</code></pre>
<pre><code class="language-java">public class ConfigTest {
 @Test
 public void test1(){
     ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
     DataSource dataSource = (DataSource) app.getBean(&quot;dataSource&quot;);
     try {
         Connection conn = dataSource.getConnection();
         System.out.println(conn);
     } catch (SQLException throwables) {
         throwables.printStackTrace();
     }
 }
}
</code></pre>
<p>正常输出对象的hash地址值</p>
</blockquote>
<h4 id="3-spring集成jnuit">③. Spring集成Jnuit</h4>
<ul>
<li>导入SpringTest的依赖</li>
</ul>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
    &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<ul>
<li>使用注解 <code>@RunWith(SpringJUnit4ClassRunner.class)</code> 替换运来的运行期</li>
<li>使用 <code>@ContextConfiguration(classes = {SpringConfiguration.class})</code> 指定配置文件或配置类</li>
<li>使用 <code>@Autowired</code> 注入需要测试的对象</li>
<li>创建测试方法进行测试</li>
</ul>
<h5 id="代码实现">代码实现</h5>
<pre><code class="language-java">@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
    @Autowired
    private DataSource dataSource;
    @Test
    public void test1(){
        try {
            Connection conn = dataSource.getConnection();
            System.out.println(conn);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
</code></pre>
<h3 id="7-aop">7. AOP</h3>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-aop&lt;/artifactId&gt;
    &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;cglib&lt;/groupId&gt;
    &lt;artifactId&gt;cglib&lt;/artifactId&gt;
    &lt;version&gt;3.3.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.aspectj&lt;/groupId&gt;
    &lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt;
    &lt;version&gt;1.9.6&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<h4 id="1-概述">①. 概述</h4>
<blockquote>
<p>AOP是Aspect Oriented Programming的缩写，意思是面向切面编程，是通过预编译方式和运行期动态代理实现程序功能统一维护的一种技术</p>
</blockquote>
<h4 id="2-作用">②. 作用</h4>
<blockquote>
<p>AOP是OOP的延续，是Spring框架中一个重要内容，是函数式编程的一种衍生，利用AOP可以对业务逻辑各个部分进行隔离，从而使得业务逻辑各部分之间的耦合度降低，提高程序的可用性，同时提高了开发效率</p>
</blockquote>
<ul>
<li>在不修改源码的情况下对方法的功能进行增强</li>
<li>优点：减少重复代码，提高开发效率，便于维护</li>
</ul>
<h4 id="3-aop底层实现">③. AOP底层实现</h4>
<ul>
<li>
<p>动态代理技术</p>
<ul>
<li>
<p>JDK代理：基于接口的动态代理对象</p>
<figure data-type="image" tabindex="2"><img src="http://pic.zyblog.xyz/img/typora/20210215125048.png" alt="image-20210215125040875" loading="lazy"></figure>
</li>
<li>
<p>CGLIB代理：基于父类的动态代理技术</p>
<figure data-type="image" tabindex="3"><img src="http://pic.zyblog.xyz/img/typora/20210215125109.png" alt="image-20210215125109151" loading="lazy"></figure>
</li>
</ul>
</li>
</ul>
<h4 id="4-相关概念">④. 相关概念</h4>
<ul>
<li><code>Target（目标对象）</code>：代理的目标对象</li>
<li><code>Proxy（代理）</code>：一个类被AOP增强后，就产生一个结果代理类</li>
<li><code>Joinpoint（连接点）</code>：被拦截到的点，在spring中指的是方法，因为spring只支持方法类型的连接点</li>
<li><code>Pointcut（切入点）</code>：指我们要对哪些Joinpoint进行拦截定义</li>
<li><code> Advice（通知/增强）</code>：指拦截到Joinpoint之后所要做的增强</li>
<li><code>Aspect（切面）</code>：是切入点和增强的结合</li>
<li><code>Weaving（织入）</code>：切入点和增强结合的过程</li>
</ul>
<blockquote>
<p>概念性的东西着重归纳出自己的见解，而不是死记硬背，像这种恶心的概念，也只有记笔记的时候，才会出现</p>
</blockquote>
<h4 id="5-xml配置aop详解">⑤. XML配置AOP详解</h4>
<ul>
<li>
<p>切点表达式</p>
<ul>
<li>语法：<code>execution([修饰符] 返回值类型 包名.类名.方法名(参数))</code></li>
<li>访问修饰符可以省略</li>
<li>返回值类型，包名，类名，方法名可以使用 <code>*</code> 代表任意</li>
<li>包名与类名之间一个点 <code>.</code> 代表当前包下的类，两个点 <code>..</code>表示当前包及其子包下的类</li>
<li>参数列表可以使用两个点 <code>..</code> 表示任意个数，任意类型的参数列表</li>
</ul>
</li>
<li>
<p>增强类型</p>
<ul>
<li>语法：<code>&lt;aop:增强类型 method=&quot;切面类中方法名&quot; pointcut=&quot;切点表达式&quot; /&gt;</code></li>
<li>增强类型
<ul>
<li>前置增强：<code>&lt;aop:before&gt;</code>：在切点方法执行之前执行</li>
<li>后置增强：<code>&lt;aop:after-returning&gt;</code>：在切点方法执行之后执行</li>
<li>环绕增强：<code>&lt;aop:around&gt;</code>：在切点方法之前之后均执行</li>
<li>异常抛出增强：<code>&lt;aop:throwing&gt;</code>：当增强方法出现异常时执行</li>
<li>最终增强：<code>&lt;aop:after&gt;</code>：在所有增强方法执行完毕时执行</li>
</ul>
</li>
</ul>
</li>
<li>
<p>代码实现</p>
<ul>
<li>
<pre><code class="language-java">public class Target {
    public void show(){
        System.out.println(&quot;show方法&quot;);
    }
}

public class MyAspect {
    public void before(){
        System.out.println(&quot;前置增强方法&quot;);
    }
    public void afterReturning(){
        System.out.println(&quot;后置增强方法&quot;);
    }
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println(&quot;前置增强方法&quot;);
        Object proceed = pjp.proceed();
        System.out.println(&quot;后置增强方法&quot;);
        return proceed;
    }
    public void afterThrowing(){
        System.out.println(&quot;增强方法出现异常&quot;);
    }
    public void after(){
        System.out.println(&quot;最终增强&quot;);
    }
}
</code></pre>
<pre><code class="language-xml">&lt;bean id=&quot;target&quot; class=&quot;com.zhiyuan.proxy.aop.Target&quot;/&gt;
&lt;bean id=&quot;aspect&quot; class=&quot;com.zhiyuan.proxy.aop.MyAspect&quot;/&gt;
&lt;aop:config&gt;
&lt;aop:aspect ref=&quot;aspect&quot;&gt;
    &lt;aop:before method=&quot;before&quot; pointcut=&quot;execution(* com.zhiyuan.proxy.aop.*.*(..))&quot;/&gt;
    &lt;aop:after-returning method=&quot;afterReturning&quot; pointcut=&quot;execution(* com.zhiyuan.proxy.aop.*.*(..))&quot;/&gt;
    &lt;aop:around method=&quot;around&quot; pointcut=&quot;execution(* com.zhiyuan.proxy.aop.*.*(..))&quot;/&gt;
    &lt;aop:after-throwing method=&quot;afterThrowing&quot; pointcut=&quot;execution(* com.zhiyuan.proxy.aop.*.*(..))&quot;/&gt;
    &lt;aop:after method=&quot;after&quot; pointcut=&quot;execution(* com.zhiyuan.proxy.aop.*.*(..))&quot;/&gt;
&lt;/aop:aspect&gt;
&lt;/aop:config&gt;
</code></pre>
</li>
</ul>
</li>
</ul>
<h4 id="6-切点表达式抽取">⑥. 切点表达式抽取</h4>
<ul>
<li>当多个增强的切点表达式相同时，可以将切点表达式进行抽取，在增强中使用 <code>pointcut-ref</code> 属性替代 <code>pointcut</code> 属性来引用抽取后的切点表达式</li>
</ul>
<pre><code class="language-xml">&lt;bean id=&quot;target&quot; class=&quot;com.zhiyuan.proxy.aop.Target&quot;/&gt;
&lt;bean id=&quot;aspect&quot; class=&quot;com.zhiyuan.proxy.aop.MyAspect&quot;/&gt;
&lt;aop:config&gt;
    &lt;aop:aspect ref=&quot;aspect&quot;&gt;
        &lt;aop:pointcut id=&quot;myPointcut&quot; expression=&quot;execution(* com.zhiyuan.proxy.aop.*.*(..))&quot;/&gt;
        &lt;aop:before method=&quot;before&quot; pointcut-ref=&quot;myPointcut&quot;/&gt;
        &lt;aop:after-returning method=&quot;afterReturning&quot; pointcut-ref=&quot;myPointcut&quot;/&gt;
        &lt;aop:around method=&quot;around&quot; pointcut-ref=&quot;myPointcut&quot;/&gt;
        &lt;aop:after-throwing method=&quot;afterThrowing&quot; pointcut-ref=&quot;myPointcut&quot;/&gt;
        &lt;aop:after method=&quot;after&quot; pointcut-ref=&quot;myPointcut&quot;/&gt;
    &lt;/aop:aspect&gt;
&lt;/aop:config&gt;
</code></pre>
<h4 id="7-注解配置aop">⑦. 注解配置AOP</h4>
<ul>
<li>
<p>配置步骤</p>
<ul>
<li>使用 <code>@Aspect</code> 标注切面类</li>
<li>使用 <code>@增强类型</code> 标注增强方法</li>
<li>在配置文件中配置aop自动代理 <code>&lt;aop:aspectj-autoproxy/&gt;</code></li>
</ul>
</li>
<li>
<p>注解增强类型</p>
<ul>
<li><code>@Before</code>：用于配置前置增强，指定增强的方法在切入点之前执行</li>
<li><code>@AfterReturning</code>：用于配置后置增强，指定增强的方法在切入点方法之后执行</li>
<li><code>@Around</code>：用于配置环绕增强，指定增强的方法在出现异常时执行</li>
<li><code>@AfterThrowing</code>：用于配置异常抛出通知，指定增强的方法在出现异常时执行</li>
<li><code>@After</code>：用于配置最终通知，无论增强方法执行是否有异常都会执行</li>
</ul>
</li>
<li>
<p>代码实现</p>
</li>
</ul>
<pre><code class="language-java">public interface TargetInterface {
    public abstract void show();
}
</code></pre>
<pre><code class="language-java">@Component(&quot;target&quot;)
public class Target implements TargetInterface{
    @Override
    public void show(){
        System.out.println(&quot;show方法&quot;);
    }
}
</code></pre>
<pre><code class="language-java">@Component(&quot;myAspect&quot;)
@Aspect
public class MyAspect {
    @Before(&quot;execution(* com.zhiyuan.proxy.anno.*.*(..))&quot;)
    public void before(){
        System.out.println(&quot;前置增强方法&quot;);
    }
    @AfterReturning(&quot;execution(* com.zhiyuan.proxy.anno.*.*(..))&quot;)
    public void afterReturning(){
        System.out.println(&quot;后置增强方法&quot;);
    }
    @Around(&quot;execution(* com.zhiyuan.proxy.anno.*.*(..))&quot;)
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println(&quot;前置增强方法&quot;);
        Object proceed = pjp.proceed();
        System.out.println(&quot;后置增强方法&quot;);
        return proceed;
    }
    @AfterThrowing(&quot;execution(* com.zhiyuan.proxy.anno.*.*(..))&quot;)
    public void afterThrowing(){
        System.out.println(&quot;增强方法出现异常&quot;);
    }
    @After(&quot;execution(* com.zhiyuan.proxy.anno.*.*(..))&quot;)
    public void after(){
        System.out.println(&quot;最终增强&quot;);
    }
}
</code></pre>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;
    &lt;!--开启组件扫描--&gt;
    &lt;context:component-scan base-package=&quot;com.zhiyuan.proxy.anno&quot;/&gt;
    &lt;!--设置AOP自动代理--&gt;
    &lt;aop:aspectj-autoproxy/&gt;
&lt;/beans&gt;
</code></pre>
<pre><code class="language-java">@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(&quot;classpath:applicationContext-anno.xml&quot;)

public class AnnoTest {
    @Autowired
    private TargetInterface target;
    @Test
    public void test1(){
        target.show();
    }
}
</code></pre>
<pre><code class="language-shell">前置增强方法
前置增强方法
show方法
后置增强方法
最终增强
后置增强方法
</code></pre>
<ul>
<li>抽取切点表达式
<ul>
<li>在切面内定义方法，在该方法上使用 <code>@Pointcut</code> 注解定义切点表达式，然后在增强注解中进行引用</li>
</ul>
</li>
<li>代码实现</li>
</ul>
<pre><code class="language-java">@Component(&quot;myAspect&quot;)
@Aspect
public class MyAspect {
    @Before(&quot;MyAspect.pointcut()&quot;)
    public void before(){
        System.out.println(&quot;前置增强方法&quot;);
    }
    @AfterReturning(&quot;pointcut()&quot;)
    public void afterReturning(){
        System.out.println(&quot;后置增强方法&quot;);
    }
    @Around(&quot;pointcut()&quot;)
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println(&quot;前置增强方法&quot;);
        Object proceed = pjp.proceed();
        System.out.println(&quot;后置增强方法&quot;);
        return proceed;
    }
    @AfterThrowing(&quot;pointcut()&quot;)
    public void afterThrowing(){
        System.out.println(&quot;增强方法出现异常&quot;);
    }
    @After(&quot;pointcut()&quot;)
    public void after(){
        System.out.println(&quot;最终增强&quot;);
    }
    @Pointcut(&quot;execution(* com.zhiyuan.proxy.anno.*.*(..))&quot;)
    public void pointcut(){}
}
</code></pre>
<h3 id="8-springjdbctemplate">8. SpringJdbcTemplate</h3>
<h4 id="1-导入依赖">①. 导入依赖</h4>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
    &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-tx&lt;/artifactId&gt;
    &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<h4 id="2-xml配置">②. xml配置</h4>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd &quot;&gt;
    &lt;!--加载配置文件--&gt;
    &lt;context:property-placeholder location=&quot;classpath:druid.properties&quot;/&gt;
    &lt;!--配置DataSource--&gt;
    &lt;bean id=&quot;dataSource&quot; class=&quot;com.alibaba.druid.pool.DruidDataSource&quot;&gt;
        &lt;property name=&quot;driverClassName&quot; value=&quot;${driverClassName}&quot;/&gt;
        &lt;property name=&quot;url&quot; value=&quot;${url}&quot;/&gt;
        &lt;property name=&quot;username&quot; value=&quot;${dbusername}&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;${password}&quot;/&gt;
    &lt;/bean&gt;
    &lt;!--配置JdbcTemplate--&gt;
    &lt;bean id=&quot;jdbcTemplate&quot; class=&quot;org.springframework.jdbc.core.JdbcTemplate&quot;&gt;
        &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<pre><code class="language-java">public class JdbcTemplateTest {
    @Test
    public void test1(){
        ApplicationContext app = new ClassPathXmlApplicationContext(&quot;applicationContext.xml&quot;);
        JdbcTemplate jdbcTemplate = (JdbcTemplate)app.getBean(&quot;jdbcTemplate&quot;);
        List&lt;User&gt; list = jdbcTemplate.query(&quot;select * from user&quot;, new BeanPropertyRowMapper&lt;User&gt;(User.class));
        for (User user : list) {
            System.out.println(user);
        }
    }
}
</code></pre>
<h3 id="9-spring的事务控制">9. Spring的事务控制</h3>
<h4 id="1-编程式事务控制">①. 编程式事务控制</h4>
<ul>
<li><code>PlatformTransactionManager</code> ：Spring的事务管理器
<ul>
<li><code>TransactionStatus getTransaction(TransactionDefination defination)</code>：获取事务状态信息</li>
<li><code>void commit(TransactionStatus status)</code>：提交事务</li>
<li><code>void rollback(TransactionStatus status)</code>：回滚事务</li>
</ul>
</li>
<li><code>TransactionDefination</code>：事务信息对象
<ul>
<li><code>int getIsolationLevel()</code>：获取事务的隔离级别</li>
<li><code>int getPropogationBehavior</code>：获取事务的传播行为</li>
<li><code>int getTimeout()</code>：获取超时时间</li>
<li><code>boolean isReadOnly()</code>：是否只读</li>
</ul>
</li>
<li>事务隔离级别
<ul>
<li><code>ISOLATION_DEFAULT</code>：默认</li>
<li><code>ISOLATION_READ_UNCOMMITTED</code>：读未提交</li>
<li><code>ISOLATION_READ_COMMITTED</code>：读已提交</li>
<li><code>ISOLATION_REPEATABLE_READ</code>：可重复读</li>
<li><code>ISOLATION_SERIALIZABLE</code>：串行化</li>
</ul>
</li>
<li>事务传播行为
<ul>
<li><code>REQUIRED</code>：如果当时没有事务，就新建一个事务，如果已存在一个事务中，加入到这个事务中，一般选择这一项（默认值）</li>
<li><code>SUPPORTS</code>：支持当前事务，如果当前没有事务，就以非事务方式执行</li>
<li><code>MANDATORY</code>：使用当前的事务，如果当前没有事务，就抛出异常</li>
<li><code>REQUES_NEW</code>：新建事务，如果当前在事务中，就把当前事务挂起</li>
<li><code>NOT_SUPPORTED</code>：以非事务方式执行操作，如果当前存在事务，就把当前事务挂起</li>
<li><code>NEVER</code>：以非事务方式运行，如果当前存在事务，抛出异常</li>
<li><code>NESTED</code>：如果当前存在事务，则在嵌套事务内执行，如果当前没有实物，则执行 <code>REQUIRED</code> 类似的操作</li>
<li>超时时间：默认值为-1，没有超时限制，单位为秒可设置超时时间</li>
<li>是否只读：建议查询时设置为只读</li>
</ul>
</li>
<li><code>TransactionStatus</code>：事务状态信息
<ul>
<li><code>boolean hasSavepoint()</code>：是否存储回滚点</li>
<li><code>boolean isCompleted()</code>：事务是否完成</li>
<li><code>boolean isNewTransaction()</code>：是否是新事务</li>
<li><code>boolean isRollbackOnly()</code>：事务是否回滚</li>
</ul>
</li>
</ul>
<h4 id="2-声明式事务控制">②. 声明式事务控制</h4>
<ul>
<li>
<p>Spring声明式事务控制底层就是AOP</p>
</li>
<li>
<p>基于xml配置实现</p>
<ul>
<li>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
       xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd&quot;&gt;
    &lt;!--加载配置文件--&gt;
    &lt;context:property-placeholder location=&quot;classpath:druid.properties&quot;/&gt;
    &lt;!--配置DataSource--&gt;
    &lt;bean id=&quot;dataSource&quot; class=&quot;com.alibaba.druid.pool.DruidDataSource&quot;&gt;
        &lt;property name=&quot;driverClassName&quot; value=&quot;${driverClassName}&quot;/&gt;
        &lt;property name=&quot;url&quot; value=&quot;${url}&quot;/&gt;
        &lt;property name=&quot;username&quot; value=&quot;${dbusername}&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;${password}&quot;/&gt;
    &lt;/bean&gt;
    &lt;!--配置JdbcTemplate--&gt;
    &lt;bean id=&quot;jdbcTemplate&quot; class=&quot;org.springframework.jdbc.core.JdbcTemplate&quot;&gt;
        &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;
    &lt;/bean&gt;
    &lt;bean id=&quot;userDao&quot; class=&quot;com.zhiyuan.dao.impl.UserDaoImpl&quot;&gt;
        &lt;property name=&quot;jdbcTemplate&quot; ref=&quot;jdbcTemplate&quot;/&gt;
    &lt;/bean&gt;
    &lt;bean id=&quot;userService&quot; class=&quot;com.zhiyuan.service.impl.UserServiceImpl&quot;&gt;
        &lt;property name=&quot;userDao&quot; ref=&quot;userDao&quot;/&gt;
    &lt;/bean&gt;
    &lt;!--配置平台事务管理对象--&gt;
    &lt;bean id=&quot;transactionManager&quot; class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot;&gt;
        &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;
    &lt;/bean&gt;
    &lt;!--增强事务--&gt;
    &lt;tx:advice id=&quot;txAdvice&quot; transaction-manager=&quot;transactionManager&quot;&gt;
        &lt;tx:attributes&gt;
            &lt;tx:method name=&quot;transfer&quot; isolation=&quot;REPEATABLE_READ&quot; propagation=&quot;REQUIRED&quot; read-only=&quot;false&quot;/&gt;
            &lt;tx:method name=&quot;*&quot; isolation=&quot;DEFAULT&quot; propagation=&quot;REQUIRED&quot; timeout=&quot;-1&quot; read-only=&quot;false&quot;/&gt;
        &lt;/tx:attributes&gt;
    &lt;/tx:advice&gt;
    &lt;!--配置事务的织入--&gt;
    &lt;aop:config&gt;
        &lt;aop:advisor advice-ref=&quot;txAdvice&quot; pointcut=&quot;execution(* com.zhiyuan.service.impl.*.*(..))&quot;/&gt;
    &lt;/aop:config&gt;
&lt;/beans&gt;
</code></pre>
</li>
</ul>
</li>
<li>
<p>基于注解配置实现</p>
<ul>
<li>使用 <code>@Transactional</code> 在需要进行事务控制的类或是方法上修饰，注解可用的属性同xml的配置方式</li>
<li>注解使用在类上，那么该类下所有方法都是用同一套注解参数配置</li>
<li>使用在方法上，不同的方法可以采用不同的事务参数配置</li>
<li>xml配置文件中要开启事务的注解驱动 <code>&lt;tx:annotation-driven&gt;</code></li>
<li>事务控制配置建议使用xml配置</li>
</ul>
</li>
</ul>
<h3 id="10-spring与web环境的集成">10. Spring与web环境的集成</h3>
<h4 id="1-applicationcontext的获取">①. ApplicationContext的获取</h4>
<ul>
<li>
<p>使用 <code>ServletContextListener</code> 监听web应用的启动，在 <code>ServletContext</code> 被创建时，创建 <code>ApplicationContext</code> 对象并存储到 <code>ServletContext</code> 域中，这样就可以在当前项目的任意位置获取到Spring容器</p>
</li>
<li>
<p>Spring提供了一个监听器 <code>ContextLoaderListener</code> 就是对上述功能的封装，该监听器内部加载Spring配置文件，创建了Spring容器对象，并存储到ServletContext域中，提供一个工具类供使用者获得Spring容器对象</p>
</li>
<li>
<p>使用步骤</p>
<ul>
<li>导入 <code>spring-web</code> 坐标</li>
<li>在 <code>web.xml</code> 中配置 <code>ContextLoaderListener</code> 监听器</li>
<li>使用 <code>WebApplicationContextUtils</code> 获得应用上下文对象 <code>ApplicationContext</code></li>
</ul>
</li>
<li>
<p>代码实现</p>
<ul>
<li>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
    &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
</li>
<li>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd&quot;
         version=&quot;4.0&quot;&gt;
    &lt;context-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;classpath:applicationContext.xml&lt;/param-value&gt;
    &lt;/context-param&gt;
    &lt;listener&gt;
        &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
    &lt;/listener&gt;
&lt;/web-app&gt;
</code></pre>
</li>
<li>
<pre><code class="language-java">ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
</code></pre>
</li>
</ul>
</li>
</ul>
<h2 id="二-springmvc">二、SpringMVC</h2>
<ul>
<li>SpringMVC是一种基于Java实现MVC设计模式的请求驱动类型的轻量级web框架，属于SpringFrameWork的后续产品，已经融合在 SpringWebFlow 中</li>
<li>它通过一套注解，让一个简单的Java类成为处理请求的控制器，而无序实现任何接口，同时它还支持RESTful 编程风格的请求</li>
</ul>
<blockquote>
<p>RestFul请求规范：</p>
<p>get：查询数据</p>
<p>post：添加数据</p>
<p>put：修改数据</p>
<p>delete：删除数据</p>
</blockquote>
<h3 id="1-开发步骤">1. 开发步骤</h3>
<h4 id="1-导入springmvc的依赖">①. 导入SpringMVC的依赖</h4>
<h4 id="2-配置springmvc核心控制器dispatcherservlet">②. 配置SpringMVC核心控制器DispatcherServlet</h4>
<h4 id="3-编写controller业务和view页面">③. 编写Controller业务和View页面</h4>
<h4 id="4-将controller使用注解配置到spring容器中">④. 将Controller使用注解配置到Spring容器中</h4>
<h4 id="5-配置spring-mvcxml文件配置组件扫描">⑤. 配置spring-mvc.xml文件（配置组件扫描）</h4>
<h4 id="6-客户端发起请求测试">⑥. 客户端发起请求测试</h4>
<h3 id="2-代码实现">2. 代码实现</h3>
<ul>
<li>导入SpringMVC依赖</li>
</ul>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
    &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<ul>
<li>配置Servlet</li>
</ul>
<pre><code class="language-xml">&lt;!--配置SpringMVC的前端控制器--&gt;
&lt;servlet&gt;
    &lt;servlet-name&gt;DispatcherServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;classpath:springmvc.xml&lt;/param-value&gt;
    &lt;/init-param&gt;
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;DispatcherServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</code></pre>
<ul>
<li>编写Controller</li>
</ul>
<pre><code class="language-java">@Controller
public class UserController extends HttpServlet {
    @RequestMapping(&quot;/show&quot;)
    public String show(){
        System.out.println(&quot;show地址映射&quot;);
        return &quot;new.jsp&quot;;
    }
}
</code></pre>
<ul>
<li>配置SpringMVC配置文件组件扫描</li>
</ul>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;
    &lt;context:component-scan base-package=&quot;com.zhiyuan.controller&quot;/&gt;
&lt;/beans&gt;
</code></pre>
<h3 id="3-流程图示">3. 流程图示</h3>
<figure data-type="image" tabindex="4"><img src="http://pic.zyblog.xyz/img/typora/20210222094947.png" alt="image-20210222094937825" loading="lazy"></figure>
<h3 id="4-执行流程">4. 执行流程</h3>
<figure data-type="image" tabindex="5"><img src="http://pic.zyblog.xyz/img/typora/20210303095152.png" alt="image-20210303095145331" loading="lazy"></figure>
<h4 id="1-用户发送请求到前端控制器dispatcherservlet">①. 用户发送请求到前端控制器DispatcherServlet</h4>
<h4 id="2-dispatcherservlet收到请求调用handlermapping处理器映射器">②. DispatcherServlet收到请求调用HandlerMapping处理器映射器</h4>
<h4 id="3-处理器映射器找到具体的处理器可以根据xml或者注解进行查找生成处理器对象及处理器拦截器如果有则生成一并返回给dispatcherservlet">③. 处理器映射器找到具体的处理器（可以根据xml或者注解进行查找），生成处理器对象及处理器拦截器（如果有则生成）一并返回给DispatcherServlet</h4>
<h4 id="4-disptcherservlet调用handleradaptor处理器适配器">④. DisptcherServlet调用HandlerAdaptor处理器适配器</h4>
<h4 id="5-handleradaptor经过适配器调用具体的处理器controller也叫后端控制器">⑤. HandlerAdaptor经过适配器调用具体的处理器（Controller，也叫后端控制器）</h4>
<h4 id="6-controller执行完成返回modelandview">⑥. Controller执行完成返回ModelAndView</h4>
<h4 id="7-handleradaptor将controller执行结modelandview返回给dispatcherservlet">⑦. HandlerAdaptor将controller执行结ModelAndView返回给DispatcherServlet</h4>
<h4 id="8-dispatcherservlet将modelandview传给viewreslover视图解析器">⑧. DispatcherServlet将ModelAndView传给ViewReslover视图解析器</h4>
<h4 id="9-viewreslover解析后返回具体view">⑨. ViewReslover解析后返回具体View</h4>
<h4 id="10-dispatcherservlet根据view进行渲染视图将模型数据填充至视图中由dispatcherservlet响应用户">⑩. DispatcherServlet根据View进行渲染视图（将模型数据填充至视图中），由DispatcherServlet响应用户</h4>
<h3 id="5-springmvc注解解析">5. SpringMVC注解解析</h3>
<h4 id="1-requestmapping">①. <code>@RequestMapping</code></h4>
<ul>
<li>用在类上
<ul>
<li>映射模块路径：请求URL的一级访问目录，如果类上不加，默认为根目录</li>
</ul>
</li>
<li>用在方法上
<ul>
<li>映射方法路径：请求URL的二级访问目录，与类上的目录组合完成指定方法的访问</li>
</ul>
</li>
<li>属性
<ul>
<li>value：用于指定请求的URL</li>
<li>method：用于指定请求的方式 <code>值建议使用RequestMethod枚举类型</code></li>
<li>params：用于指定限制请求参数的条件，它支持简单的表达式，要求请求参数的key和value必须和配置的一模一样</li>
</ul>
</li>
</ul>
<h3 id="6-springmvc的xml配置">6. SpringMVC的xml配置</h3>
<pre><code class="language-xml">&lt;!--开启Controller注解扫描--&gt;
&lt;context:component-scan base-package=&quot;com.zhiyuan.controller&quot;&gt;
    &lt;context:include-filter type=&quot;annotation&quot; expression=&quot;org.springframework.stereotype.Controller&quot;/&gt;
&lt;/context:component-scan&gt;
&lt;!--注册处理器映射器--&gt;
&lt;bean id=&quot;handlerMapping&quot; class=&quot;org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping&quot;/&gt;
&lt;!--注册处理器适配器--&gt;
&lt;bean class=&quot;org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter&quot;&gt;
    &lt;property name=&quot;messageConverters&quot;&gt;
        &lt;list&gt;
            &lt;bean id=&quot;stringConverter&quot; class=&quot;org.springframework.http.converter.StringHttpMessageConverter&quot;&gt;
                &lt;property name=&quot;supportedMediaTypes&quot;&gt;
                    &lt;list&gt;
                        &lt;value&gt;text/html;charset=UTF-8&lt;/value&gt;
                        &lt;value&gt;application/json;charset=UTF-8&lt;/value&gt;
                        &lt;value&gt;text/plain;charset=UTF-8&lt;/value&gt;
                    &lt;/list&gt;
                &lt;/property&gt;
            &lt;/bean&gt;
            &lt;bean id=&quot;jsonConverter&quot; class=&quot;org.springframework.http.converter.json.MappingJackson2HttpMessageConverter&quot;&gt;
                &lt;property name=&quot;supportedMediaTypes&quot;&gt;
                    &lt;list&gt;
                        &lt;value&gt;text/html;charset=UTF-8&lt;/value&gt;
                        &lt;value&gt;application/json;charset=UTF-8&lt;/value&gt;
                        &lt;value&gt;text/plain;charset=UTF-8&lt;/value&gt;
                    &lt;/list&gt;
                &lt;/property&gt;
            &lt;/bean&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;
&lt;!--注册内部视图解析器--&gt;
&lt;bean id=&quot;viewResolver&quot; class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
    &lt;property name=&quot;prefix&quot; value=&quot;/jsp/&quot;/&gt;
    &lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot;/&gt;
&lt;/bean&gt;
</code></pre>
<h3 id="7-springmvc的相关组件">7. SpringMVC的相关组件</h3>
<ul>
<li>前端控制器：DisptcherServlet（SpringMVC提供的分发请求的Servlet，需要我们在web.xml中配置）</li>
<li>处理器映射器：HandlerMapping（SpringMVC提供的映射容器）</li>
<li>处理器适配器：HandlerAdapter（SpringMVC提供的处理器适配器）</li>
<li>处理器：Handler（需要我们写的Controller）</li>
<li>视图解析器：ViewResolver（SpringMVC提供的资源视图解析器）</li>
<li>视图：View</li>
</ul>
<h3 id="8-springmvc数据响应方式">8. SpringMVC数据响应方式</h3>
<h4 id="1-页面跳转">①. 页面跳转</h4>
<ul>
<li>
<p>直接返回字符串：这种方式会将返回的字符串与视图解析器的前后缀拼接后跳转</p>
<pre><code class="language-java">@RequestMapping(&quot;/test&quot;)
public String test(){
    return &quot;index.jsp&quot;;
}
</code></pre>
</li>
<li>
<p>通过ModelAndView对象返回</p>
<pre><code class="language-java">@RequestMapping(&quot;/test&quot;)
public ModelAndView test(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName(&quot;new&quot;);
    modelAndView.addObject(&quot;username&quot;,&quot;zhiyuan&quot;);
    return modelAndView;
}

@RequestMapping(&quot;/test2&quot;)
public ModelAndView test2(ModelAndView modelAndView){
	modelAndView.setViewName(&quot;new&quot;);
    modelAndView.addObject(&quot;username&quot;,&quot;zhiyuan&quot;);
    return modelAndView;
}

@RequestMapping(&quot;/test3&quot;)
public Model test3(Model model){
    model.addAttribute(&quot;username&quot;,&quot;张三&quot;);
    return model;
}

@RequestMapping(&quot;/test4&quot;)
public String test4(HttpServletRequest request,HttpServletResponse response){
    request.setAttribute(&quot;username&quot;,&quot;张三&quot;);
    return &quot;index.jsp&quot;;
} 
</code></pre>
</li>
</ul>
<h4 id="2-回写数据">②. 回写数据</h4>
<ul>
<li>
<p>直接返回字符串</p>
<pre><code class="language-java">@RequestMapping(&quot;/test3&quot;)
@ResponseBody
public String test3(HttpServletResponse response){
    response.setContentType(&quot;text/html;charset=utf-8&quot;);
    return &quot;直接回写字符串&quot;;
}
</code></pre>
</li>
<li>
<p>返回对象或集合</p>
<pre><code class="language-xml">&lt;!--配置处理器映射器--&gt;
&lt;bean class=&quot;org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter&quot;&gt;
    &lt;property name=&quot;messageConverters&quot;&gt;
        &lt;list&gt;
            &lt;bean id=&quot;stringConverter&quot; class=&quot;org.springframework.http.converter.StringHttpMessageConverter&quot;&gt;
                &lt;property name=&quot;supportedMediaTypes&quot;&gt;
                    &lt;list&gt;
                        &lt;value&gt;text/html;charset=UTF-8&lt;/value&gt;
                        &lt;value&gt;application/json;charset=UTF-8&lt;/value&gt;
                        &lt;value&gt;text/plain;charset=UTF-8&lt;/value&gt;
                    &lt;/list&gt;
                &lt;/property&gt;
            &lt;/bean&gt;
            &lt;bean id=&quot;jsonConverter&quot; class=&quot;org.springframework.http.converter.json.MappingJackson2HttpMessageConverter&quot;&gt;
                &lt;property name=&quot;supportedMediaTypes&quot;&gt;
                    &lt;list&gt;
                        &lt;value&gt;text/html;charset=UTF-8&lt;/value&gt;
                        &lt;value&gt;application/json;charset=UTF-8&lt;/value&gt;
                        &lt;value&gt;text/plain;charset=UTF-8&lt;/value&gt;
                    &lt;/list&gt;
                &lt;/property&gt;
            &lt;/bean&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;
&lt;!--开启扫描注解驱动--&gt;
&lt;mvc:annotation-driven/&gt;
</code></pre>
<pre><code class="language-java">@RequestMapping(&quot;/test&quot;)
@ResponseBody
public Person test(){
    Person person = new Person(); 
    person.setAge(25);
    person.setGender(&quot;male&quot;);
    person.setName(&quot;张三&quot;);
    return person;
}
</code></pre>
</li>
</ul>
<h3 id="9-springmvc获得请求数据">9. SpringMVC获得请求数据</h3>
<h4 id="1-获得请求参数">①. 获得请求参数</h4>
<ul>
<li>基本类型参数</li>
<li>POJO类型参数（JavaBean）</li>
<li>数组类型参数</li>
<li>集合类型参数</li>
</ul>
<h4 id="2-获得一个基本类型参数">②. 获得一个基本类型参数</h4>
<pre><code class="language-java">@RequestMapping(&quot;/test&quot;)
@ResponseBody
public void test(String username,String age,String gender){
    System.out.println(username + &quot;\t&quot; + age + &quot;\t&quot; + gender);
}
</code></pre>
<figure data-type="image" tabindex="6"><img src="http://pic.zyblog.xyz/img/typora/20210304155111.png" alt="image-20210304155103994" loading="lazy"></figure>
<pre><code class="language-shell">张三	26	male
</code></pre>
<h4 id="3-获得一个pojo类型参数">③. 获得一个POJO类型参数</h4>
<pre><code class="language-java">@RequestMapping(&quot;/test4&quot;)
@ResponseBody
public void test4(User user){
    System.out.println(user);
}
</code></pre>
<figure data-type="image" tabindex="7"><img src="http://pic.zyblog.xyz/img/typora/20210304160053.png" alt="image-20210304160053808" loading="lazy"></figure>
<pre><code class="language-shell">User{username='张三', gender='male', age=26}
</code></pre>
<pre><code class="language-java">@RequestMapping(&quot;/test4&quot;)
@ResponseBody
public void test4(@RequestBody User user){
    System.out.println(user);
}
</code></pre>
<pre><code class="language-json">{
	&quot;username&quot;:&quot;zhiyuan&quot;,
	&quot;gender&quot;:&quot;male&quot;,
	&quot;age&quot;:26
}
</code></pre>
<pre><code class="language-java">User{username='zhiyuan', gender='male', age=26}
</code></pre>
<h4 id="4-获得一个数组类型参数">④. 获得一个数组类型参数</h4>
<pre><code class="language-java">@RequestMapping(&quot;/test5&quot;)
@ResponseBody
public void test5(String[] id){
    System.out.println(Arrays.asList(id));
}
</code></pre>
<figure data-type="image" tabindex="8"><img src="http://pic.zyblog.xyz/img/typora/20210304162014.png" alt="image-20210304162014425" loading="lazy"></figure>
<pre><code class="language-shell">[111, 222]
</code></pre>
<h4 id="5-获得一个集合类型参数一">⑤. 获得一个集合类型参数(一)</h4>
<pre><code class="language-java">package com.zhiyuan.domain;
import java.util.List;
public class VO {
    private List&lt;User&gt; userList;

    public List&lt;User&gt; getUserList() {
        return userList;
    }

    public void setUserList(List&lt;User&gt; userList) {
        this.userList = userList;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer(&quot;VO{&quot;);
        sb.append(&quot;userList=&quot;).append(userList);
        sb.append('}');
        return sb.toString();
    }
}

@RequestMapping(&quot;/test6&quot;)
@ResponseBody
public void test6(VO vo){
    System.out.println(vo);
}
</code></pre>
<figure data-type="image" tabindex="9"><img src="http://pic.zyblog.xyz/img/typora/20210304165235.png" alt="image-20210304165235811" loading="lazy"></figure>
<pre><code class="language-shell">VO{userList=[User{username='??????', gender='male', age=26}, User{username='??????', gender='female', age=22}]}
</code></pre>
<h4 id="6-获得一个集合类型参数二">⑥. 获得一个集合类型参数(二)</h4>
<pre><code class="language-jsp">&lt;%@ page contentType=&quot;text/html;charset=utf-8&quot; language=&quot;java&quot;%&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;Ajax请求&lt;/title&gt;
    &lt;script src=&quot;${pageContext.request.contextPath}/js/jquery-3.1.1.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;script&gt;
    var userList = new Array();
    userList.push({username:&quot;zhangsan&quot;,age:26});
    userList.push({username:&quot;lisi&quot;,age:28});
    $.ajax({
        type:&quot;POST&quot;,
        url:&quot;${pageContext.request.contextPath}/test7&quot;,
        data:JSON.stringify(userList),
        contentType:&quot;application/json;charset=utf-8&quot;
    });
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<pre><code class="language-java">@RequestMapping(&quot;/test7&quot;)
@ResponseBody
public void test7(@RequestBody List&lt;User&gt; userList){
    System.out.println(userList);
}
</code></pre>
<h4 id="7-开启静态资源访问">⑦. 开启静态资源访问</h4>
<pre><code class="language-xml">&lt;!--静态资源的访问--&gt;
&lt;mvc:resources mapping=&quot;/js/**&quot; location=&quot;/js/&quot;&gt;
&lt;mvc:resources mapping=&quot;/img/**&quot; location=&quot;/img/&quot;&gt;
&lt;mvc:resources mapping=&quot;/css/**&quot; location=&quot;/css/&quot;&gt;    
&lt;!--交由tomcat去寻找对应静态资源--&gt;    
&lt;mvc:default-servlet-handler/&gt;    
</code></pre>
<h4 id="8-配置全局乱码过滤器">⑧. 配置全局乱码过滤器</h4>
<pre><code class="language-xml">&lt;!--配置全局编码过滤器--&gt;
&lt;filter&gt;
    &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt;
    &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;encoding&lt;/param-name&gt;
        &lt;param-value&gt;UTF-8&lt;/param-value&gt;
    &lt;/init-param&gt;
&lt;/filter&gt;
&lt;filter-mapping&gt;
    &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
</code></pre>
<h4 id="9-参数绑定注解">⑨. 参数绑定注解</h4>
<pre><code class="language-java">@RequestMapping(&quot;/test5&quot;)
@ResponseBody
public void test5(@RequestParam(&quot;id&quot;) String[] ids){
    System.out.println(Arrays.asList(ids));
}
</code></pre>
<ul>
<li><code>@RequestParam</code>
<ul>
<li><code>value</code>：与请求参数名称进行绑定</li>
<li><code>required</code>：请求参数是否必须携带，默认为true，不携带参数请求URL会报错</li>
<li><code>defaultValue</code>：请求参数未写时默认的值</li>
</ul>
</li>
</ul>
<h3 id="10-restful风格">10. Restful风格</h3>
<blockquote>
<p>Restful风格的请求是使用 <code>URL+请求方式</code> 表示一次请求目的，HTTP协议里四个表示操作方式的动词如下</p>
<ul>
<li>GET：用于获取数据</li>
<li>POST：用户添加数据</li>
<li>PUT：用于修改数据</li>
<li>DELETE：用于删除数据</li>
</ul>
</blockquote>
<h4 id="1-restful风格请求参数的获取">①. Restful风格请求参数的获取</h4>
<pre><code class="language-java">@RequestMapping(&quot;/test8/{username}&quot;)
@ResponseBody
public void test8(@PathVariable(&quot;username&quot;) String username, HttpServletRequest request){
    System.out.println(request.getMethod()+&quot;:&quot;+username);
}
</code></pre>
<pre><code class="language-shell">GET:zhangsan
POST:zhangsan
PUT:zhangsan
DELETE:zhangsan
</code></pre>
<blockquote>
<p>因为每个方法都需要添加 <code>@ResponseBody</code></p>
<p>所以Spring为我们提供了一个解决方案 <code>@RestController</code></p>
<p>通过源码可知 <code>@RestController = @Controller + @ResponseBody</code></p>
</blockquote>
<h3 id="11-springmvc自定义类型转换器">11. SpringMVC自定义类型转换器</h3>
<blockquote>
<p>SpringMVC默认已经提供了一些常用的类型转换器，例如客户端提交的字符串转换成int型进行参数设置</p>
<p>但是并不是所有的数据类型都提供了转换器，没有提供的就需要自定义转换器，来如：日期类型的数据就需要自定义转换器</p>
</blockquote>
<h4 id="步骤">步骤</h4>
<ul>
<li>定义转换器类实现 <code>Converter</code> 接口</li>
<li>在配置文件中声明转换器</li>
<li>在 <code>&lt;annotation-driven&gt;</code> 中引用转换器</li>
</ul>
<pre><code class="language-java">public class DateConverter implements Converter&lt;String,Date&gt;{
    public Date convert(String source) {
        System.out.println(source);
        Date date = null;
        try {
            date = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;).parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
</code></pre>
<pre><code class="language-xml">&lt;mvc:annotation-driven conversion-service=&quot;conversionService&quot;/&gt;
&lt;!--声明转换器--&gt;
&lt;bean id=&quot;conversionService&quot; class=&quot;org.springframework.context.support.ConversionServiceFactoryBean&quot;&gt;
    &lt;property name=&quot;converters&quot;&gt;
        &lt;list&gt;
            &lt;bean class=&quot;com.zhiyuan.controller.DateConverter&quot;/&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;
</code></pre>
<pre><code class="language-java">@RequestMapping(&quot;/test9&quot;)
@ResponseBody
public void test9(Date date){
    System.out.println(date);
}
</code></pre>
<h3 id="12-springmvc获取请求头数据">12. SpringMVC获取请求头数据</h3>
<h4 id="1-requestheader">①. <code>@RequestHeader</code></h4>
<ul>
<li>使用 <code>@RequestHeader</code> 获取请求头信息，相当于web阶段学习的 <code>request.getHeader(name)</code></li>
<li><code>value</code>：请求头名称</li>
<li><code>required</code>：是否必须携带某请求头</li>
</ul>
<pre><code class="language-java">@RequestMapping(&quot;/test10&quot;)
@ResponseBody
public void test10(@RequestHeader(value = &quot;User-Agent&quot;,required = true) String userAgent){
    System.out.println(userAgent);
}
</code></pre>
<h4 id="2-cookievalue">②. <code>@CookieValue</code></h4>
<ul>
<li>使用 <code>@CookieValue</code> 可以获取指定Cookie的值</li>
<li><code>value</code>：指定cookie的名称</li>
<li><code>required</code>：是否必须携带某cookie</li>
</ul>
<pre><code class="language-java">@RequestMapping(&quot;/test11&quot;)
@ResponseBody
public void test11(@CookieValue(value = &quot;JSESSIONID&quot;,required = true) String sessionId){
    System.out.println(sessionId);
}
</code></pre>
<h3 id="13-springmvc文件上传">13. SpringMVC文件上传</h3>
<h4 id="1-简单上传表单">①. 简单上传表单</h4>
<pre><code class="language-html">&lt;form action=&quot;/test12&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
    用户名：&lt;input type=&quot;text&quot; name=&quot;username&quot;/&gt;&lt;br&gt;
    头像：&lt;input type=&quot;file&quot; name=&quot;upload&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;submit&quot; value=&quot;提交&quot;&gt;
&lt;/form&gt;
</code></pre>
<h4 id="2-导入依赖">②. 导入依赖</h4>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;commons-io&lt;/groupId&gt;
    &lt;artifactId&gt;commons-io&lt;/artifactId&gt;
    &lt;version&gt;2.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;commons-fileupload&lt;/groupId&gt;
    &lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt;
    &lt;version&gt;1.2.2&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<h4 id="3-配置文件上传解析器">③. 配置文件上传解析器</h4>
<pre><code class="language-xml">&lt;!--配置文件上传解析器--&gt;
&lt;!--此id必须为multipartResolver，是固定写法，不一样就是错--&gt;
&lt;bean id=&quot;multipartResolver&quot; class=&quot;org.springframework.web.multipart.commons.CommonsMultipartResolver&quot;&gt;
    &lt;!--上传文件编码类型--&gt;
    &lt;property name=&quot;defaultEncoding&quot; value=&quot;UTF-8&quot;/&gt;
    &lt;!--上传单个文件大小--&gt;
    &lt;property name=&quot;maxUploadSizePerFile&quot; value=&quot;5242880&quot;/&gt;
    &lt;!--上传文件总大小--&gt;
    &lt;property name=&quot;maxUploadSize&quot; value=&quot;5242880&quot;/&gt;
&lt;/bean&gt;
</code></pre>
<h4 id="4-编写文件上传处理代码">④. 编写文件上传处理代码</h4>
<pre><code class="language-java">@RequestMapping(value = &quot;/test12&quot;,method = RequestMethod.POST)
@ResponseBody
public void test12(@RequestParam(value = &quot;username&quot;,required = false) String username,@RequestParam(value=&quot;upload&quot;,required=false) MultipartFile upload){
    System.out.println(username);
    System.out.println(upload);
    String originalFilename = upload.getOriginalFilename();
    upload.transferTo(new File(&quot;F:\\upload\\&quot;+ MyUtils.getUUID() + originalFilename));
}
</code></pre>
<h3 id="14-springmvc多文件上传">14. SpringMVC多文件上传</h3>
<h4 id="1-简单上传表单-2">①. 简单上传表单</h4>
<pre><code class="language-html">&lt;form action=&quot;/test13&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
    用户名：&lt;input type=&quot;text&quot; name=&quot;username&quot;/&gt;&lt;br&gt;
    头像：&lt;input type=&quot;file&quot; name=&quot;upload&quot;&gt;&lt;br&gt;
    头像：&lt;input type=&quot;file&quot; name=&quot;upload&quot;&gt;&lt;br&gt;
    头像：&lt;input type=&quot;file&quot; name=&quot;upload&quot;&gt;&lt;br&gt;
    头像：&lt;input type=&quot;file&quot; name=&quot;upload&quot;&gt;&lt;br&gt;
    &lt;input type=&quot;submit&quot; value=&quot;提交&quot;&gt;
&lt;/form&gt;
</code></pre>
<h4 id="2-编写文件上传处理代码">②. 编写文件上传处理代码</h4>
<pre><code class="language-java">@RequestMapping(&quot;/test13&quot;)
@ResponseBody
public void test13(@RequestParam(value = &quot;username&quot;,required = false) String username,@RequestParam(value = &quot;upload&quot;,required = false) MultipartFile [] uploads) throws IOException {
    System.out.println(username);
    for (MultipartFile upload : uploads) {
        String originalFilename = upload.getOriginalFilename();
        upload.transferTo(new File(&quot;F:\\upload\\&quot; + MyUtils.getUUID() + originalFilename));
    }
}
</code></pre>
<h3 id="15-springmvc拦截器">15. SpringMVC拦截器</h3>
<blockquote>
<p>拦截器Interceptor相当于web阶段的过滤器Filter</p>
</blockquote>
<table>
<thead>
<tr>
<th>区别</th>
<th>过滤器</th>
<th>拦截器</th>
</tr>
</thead>
<tbody>
<tr>
<td>使用范围</td>
<td>servlet规范中的一部分，任何Web工程都可以使用</td>
<td>SpringMVC自己的部分，需要使用SpringMVC框架才能使用</td>
</tr>
<tr>
<td>拦截范围</td>
<td>在web.xml中配偶之url-pattern映射为/*时，可以拦截所有资源</td>
<td>只拦截控制器方法，对静态资源不进行拦截</td>
</tr>
</tbody>
</table>
<h4 id="1-自定义拦截器">①. 自定义拦截器</h4>
<ul>
<li>
<p>创建拦截器类实现 <code>HandlerInterceptor</code></p>
</li>
<li>
<p>配置拦截器</p>
</li>
<li>
<p>代码实现</p>
<pre><code class="language-java">public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(&quot;被拦截的方法执行之前执行preHandle方法&quot;);
        //放行请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(&quot;被拦截方法执行之后，视图返回之前执行postHandle方法&quot;);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(&quot;所有流程执行完毕，执行afterCompletion方法&quot;);
    }
}
</code></pre>
<pre><code class="language-xml">&lt;mvc:interceptors&gt;
    &lt;mvc:interceptor&gt;
        &lt;mvc:mapping path=&quot;/**&quot;/&gt;
        &lt;bean class=&quot;com.zhiyuan.interceptor.MyInterceptor&quot;/&gt;
    &lt;/mvc:interceptor&gt;
&lt;/mvc:interceptors&gt;
</code></pre>
</li>
</ul>
<h4 id="2-拦截器方法">②. 拦截器方法</h4>
<ul>
<li><code>preHandle()</code>：在请求映射的方法被调用之前，调用该方法，方法返回值为布尔型，用于控制请求是否放行，为 <code>true</code> 放行，为 <code>false</code> 不放行</li>
<li><code>postHandle()</code>：在请求映射方法执行之后，<code>DispatcherServlet</code>视图渲染之前被调用，可以在方法中操作修改<code>ModelAndView</code>对象</li>
<li><code>afterCompletion()</code>：在整个请求结束后被调用，也就是在<code>DispatcherServlet</code>渲染视图之后执行</li>
</ul>
<h3 id="16-springmvc异常处理">16. SpringMVC异常处理</h3>
<ul>
<li>
<p>编译时异常和运行时异常：前者通过捕获异常从而获取异常信息，后者主要通过规范代码开发、测试来减少运行时异常的发生</p>
</li>
<li>
<p>异常处理思路</p>
<ul>
<li>通过throws Exception向上抛出，最后由SpringMVC前端控制器交由异常处理器进行处理，如下图：</li>
</ul>
<figure data-type="image" tabindex="10"><img src="http://pic.zyblog.xyz/img/typora/20210310131408.png" alt="image-20210310131401638" loading="lazy"></figure>
</li>
<li>
<p>异常处理两种方式</p>
<ul>
<li>使用SpringMVC提供的简单异常处理器 <code>SimpleMappingExceptionResolver</code></li>
<li>实现Spring的异常处理接口 <code>HandlerExceptionResolver</code> 自定义异常处理器</li>
</ul>
</li>
</ul>
<h4 id="1-简单异常处理器">①. 简单异常处理器</h4>
<ul>
<li>配置简单异常处理器</li>
</ul>
<pre><code class="language-xml">&lt;!--配置异常处理器--&gt;
&lt;bean class=&quot;org.springframework.web.servlet.handler.SimpleMappingExceptionResolver&quot;&gt;
    &lt;property name=&quot;defaultErrorView&quot; value=&quot;error&quot;/&gt;
    &lt;property name=&quot;exceptionMappings&quot;&gt;
        &lt;map&gt;
            &lt;entry key=&quot;java.lang.ClassCastException&quot; value=&quot;error&quot;/&gt;
            &lt;entry key=&quot;java.lang.NullPointerException&quot; value=&quot;error&quot;/&gt;
        &lt;/map&gt;
    &lt;/property&gt;
&lt;/bean&gt;
</code></pre>
<h4 id="2-自定义异常处理器">②. 自定义异常处理器</h4>
<pre><code class="language-java">public class MyException extends Exception{}
</code></pre>
<pre><code class="language-java">public class MyExceptionResolver implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        if(ex instanceof MyException){
            modelAndView.addObject(&quot;info&quot;,&quot;自定义异常&quot;);
        }else if (ex instanceof ClassCastException){
            modelAndView.addObject(&quot;info&quot;,&quot;类型转换异常&quot;);
        }else{
            modelAndView.addObject(&quot;info&quot;,&quot;其他异常&quot;);
        }
        return modelAndView;
    }
}
</code></pre>
<pre><code class="language-xml">&lt;!--配置自定义异常处理器--&gt;
&lt;bean class=&quot;com.zhiyuan.resolver.MyExceptionResolver&quot;/&gt; 
</code></pre>
<h2 id="三-案例练习">三、案例练习</h2>
<h3 id="1-spring环境搭建">1. Spring环境搭建</h3>
<h4 id="1-配置-applicationcontextxml">①. 配置 applicationContext.xml</h4>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;
    &lt;!--1. 配置组件扫描--&gt;
    &lt;context:component-scan base-package=&quot;com.zhiyuan&quot;/&gt;
    &lt;!--2. 加载数据库配置文件--&gt;
    &lt;context:property-placeholder location=&quot;classpath:jdbc.properties&quot;/&gt;
    &lt;!--3. 配置数据库连接池对象--&gt;
    &lt;bean id=&quot;dataSource&quot; class=&quot;com.mchange.v2.c3p0.ComboPooledDataSource&quot;&gt;
        &lt;property name=&quot;driverClass&quot; value=&quot;${c3p0.driverClass}&quot;/&gt;
        &lt;property name=&quot;jdbcUrl&quot; value=&quot;${c3p0.jdbcUrl}&quot;/&gt;
        &lt;property name=&quot;user&quot; value=&quot;${c3p0.user}&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;${c3p0.password}&quot;/&gt;
    &lt;/bean&gt;
    &lt;!--4. 配置JdbcTemplate对象--&gt;
    &lt;bean id=&quot;jdbcTemplate&quot; class=&quot;org.springframework.jdbc.core.JdbcTemplate&quot;&gt;
        &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<h4 id="2-配置-spring-mvcxml">②. 配置 spring-mvc.xml</h4>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:mvc=&quot;http://www.springframework.org/schema/mvc&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd&quot;&gt;

    &lt;!--1. 配置mvc注解驱动--&gt;
    &lt;mvc:annotation-driven/&gt;
    &lt;!--2. 交给tomcat去寻找静态资源--&gt;
    &lt;mvc:default-servlet-handler/&gt;
    &lt;!--3. 配置内部视图解析器--&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
        &lt;property name=&quot;prefix&quot; value=&quot;/pages/&quot;/&gt;
        &lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot;/&gt;
    &lt;/bean&gt;
    &lt;!--配置文件上传解析器--&gt;
    &lt;!--此id必须为multipartResolver，是固定写法，不一样就是错--&gt;
    &lt;bean id=&quot;multipartResolver&quot; class=&quot;org.springframework.web.multipart.commons.CommonsMultipartResolver&quot;&gt;
        &lt;!--上传文件编码类型--&gt;
        &lt;property name=&quot;defaultEncoding&quot; value=&quot;UTF-8&quot;/&gt;
        &lt;!--上传单个文件大小--&gt;
        &lt;property name=&quot;maxUploadSizePerFile&quot; value=&quot;5242880&quot;/&gt;
        &lt;!--上传文件总大小--&gt;
        &lt;property name=&quot;maxUploadSize&quot; value=&quot;5242880&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<h4 id="3-配置-webxml">③. 配置 web.xml</h4>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd&quot; version=&quot;4.0&quot;&gt;
  &lt;!--配置全局编码过滤器--&gt;
  &lt;filter&gt;
    &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt;
    &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt;
    &lt;init-param&gt;
      &lt;param-name&gt;encoding&lt;/param-name&gt;
      &lt;param-value&gt;UTF-8&lt;/param-value&gt;
    &lt;/init-param&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
    &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  &lt;!--配置Spring容器--&gt;
  &lt;context-param&gt;
    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
    &lt;param-value&gt;classpath:applicationContext.xml&lt;/param-value&gt;
  &lt;/context-param&gt;
  &lt;listener&gt;
    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
  &lt;/listener&gt;
  &lt;!--配置SpringMVC的前端控制器--&gt;
  &lt;servlet&gt;
    &lt;servlet-name&gt;DispatcherServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
    &lt;init-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;classpath:spring-mvc.xml&lt;/param-value&gt;
    &lt;/init-param&gt;
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;DispatcherServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
&lt;/web-app&gt;
</code></pre>
<h4 id="4-配置-jdbcproperties">④. 配置 jdbc.properties</h4>
<pre><code class="language-properties">c3p0.driverClass=com.mysql.cj.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/test?useUnicode=ture&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=Hongkong
c3p0.user=root
c3p0.password=123456
c3p0.initialPoolSize=10
c3p0.maxPoolSize=100
c3p0.checkoutTimeout=3000
</code></pre>
<h4 id="5-配置-pomxml">⑤. 配置 pom.xml</h4>
<pre><code class="language-xml">&lt;dependencies&gt;
&lt;dependency&gt;
  &lt;groupId&gt;mysql&lt;/groupId&gt;
  &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
  &lt;version&gt;8.0.21&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;c3p0&lt;/groupId&gt;
  &lt;artifactId&gt;c3p0&lt;/artifactId&gt;
  &lt;version&gt;0.9.1.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.alibaba&lt;/groupId&gt;
  &lt;artifactId&gt;druid&lt;/artifactId&gt;
  &lt;version&gt;1.1.10&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;junit&lt;/groupId&gt;
  &lt;artifactId&gt;junit&lt;/artifactId&gt;
  &lt;version&gt;4.12&lt;/version&gt;
  &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.springframework&lt;/groupId&gt;
  &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
  &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.springframework&lt;/groupId&gt;
  &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
  &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.springframework&lt;/groupId&gt;
  &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
  &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.springframework&lt;/groupId&gt;
  &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
  &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
  &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
  &lt;version&gt;3.0.1&lt;/version&gt;
  &lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt;
  &lt;artifactId&gt;javax.servlet.jsp-api&lt;/artifactId&gt;
  &lt;version&gt;2.2.1&lt;/version&gt;
  &lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
  &lt;artifactId&gt;jackson-core&lt;/artifactId&gt;
  &lt;version&gt;2.9.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
  &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
  &lt;version&gt;2.9.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
  &lt;artifactId&gt;jackson-annotations&lt;/artifactId&gt;
  &lt;version&gt;2.9.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;commons-fileupload&lt;/groupId&gt;
  &lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt;
  &lt;version&gt;1.3.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;commons-io&lt;/groupId&gt;
  &lt;artifactId&gt;commons-io&lt;/artifactId&gt;
  &lt;version&gt;2.3&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;commons-logging&lt;/groupId&gt;
  &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
  &lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
  &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt;
  &lt;version&gt;1.7.7&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;log4j&lt;/groupId&gt;
  &lt;artifactId&gt;log4j&lt;/artifactId&gt;
  &lt;version&gt;1.2.17&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.springframework&lt;/groupId&gt;
  &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
  &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.springframework&lt;/groupId&gt;
  &lt;artifactId&gt;spring-tx&lt;/artifactId&gt;
  &lt;version&gt;5.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt;
  &lt;artifactId&gt;jstl-api&lt;/artifactId&gt;
  &lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>
<h3 id="2-业务代码">2. 业务代码</h3>
<h2 id="四-mybatis">四、 MyBatis</h2>
<h3 id="1-mybatis简介">1. MyBatis简介</h3>
<ul>
<li>MyBatis是一个优秀的基于Java的持久层框架，它内部封装了JDBC，是开发者只需要关住 SQL语句本身，而不需要花费精力器处理加载驱动、创建Connection连接对象、创建Statement对象等繁杂的过程</li>
<li>MyBatis通过XML和注解的方式将要执行的各种Statement对象配置起来，并通过Java对象和Statement中SQL语句的动态参数进行映射最终生成可执行的SQL语句</li>
<li>最后MyBatis框架执行SQL并将结果映射为Java对象并返回，采用ORM思想解决了实体和数据库的映射问题，对JDBC进行了封装，屏蔽了JDBC的API底层访问细节，使我们不用与JDBC的API打交道就可以完成对数据库的持久化操作</li>
</ul>
<h3 id="2-mybatis开发步骤">2. MyBatis开发步骤</h3>
<h4 id="1-添加mybatis的坐标">①. 添加MyBatis的坐标</h4>
<h4 id="2-创建user数据表">②. 创建user数据表</h4>
<h4 id="3-编写user实体类">③. 编写User实体类</h4>
<h4 id="4-编写映射文件usermapperxml">④. 编写映射文件UserMapper.xml</h4>
<h4 id="5-编写核心文件sqlmapconfigxml">⑤. 编写核心文件SqlMapConfig.xml</h4>
<h4 id="6-编写持久层代码">⑥. 编写持久层代码</h4>
<h3 id="3-mybatis查询数据">3. MyBatis查询数据</h3>
<blockquote>
<p>只有一个参数时建议使用 <code>${value}</code> ，用在like模糊查询</p>
</blockquote>
<pre><code class="language-xml">&lt;!--UserMapper.xml--&gt;
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;
&lt;mapper namespace=&quot;userMapper&quot;&gt;
    &lt;select id=&quot;findAll&quot; resultType=&quot;com.zhiyuan.mybatis.entity.User&quot;&gt;
        select * from user
    &lt;/select&gt;
&lt;/mapper&gt;
</code></pre>
<pre><code class="language-xml">&lt;!--SqlMapConfig.xml--&gt;
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE configuration
        PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot;
        &quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;&gt;
&lt;configuration&gt;
    &lt;environments default=&quot;development&quot;&gt;
        &lt;environment id=&quot;development&quot;&gt;
            &lt;transactionManager type=&quot;JDBC&quot;/&gt;
            &lt;dataSource type=&quot;POOLED&quot;&gt;
                &lt;property name=&quot;driver&quot; value=&quot;com.mysql.cj.jdbc.Driver&quot;/&gt;
                &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost/test?serverTimezone=Asia/Shanghai&amp;amp;useUnicode=true&amp;amp;characterEncoding=utf8&amp;amp;useSSL=true&quot;/&gt;
                &lt;property name=&quot;username&quot; value=&quot;root&quot;/&gt;
                &lt;property name=&quot;password&quot; value=&quot;123456&quot;/&gt;
            &lt;/dataSource&gt;
        &lt;/environment&gt;
    &lt;/environments&gt;
    &lt;mappers&gt;
        &lt;mapper resource=&quot;com/zhiyuan/mapper/UserMapper.xml&quot;/&gt;
    &lt;/mappers&gt;
&lt;/configuration&gt;
</code></pre>
<pre><code class="language-java">@Test
public void test1() throws IOException {
    //读取核心配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);
    //创建会话工厂
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //创建会话对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //执行sql返回结果
    List&lt;User&gt; userList = sqlSession.selectList(&quot;userMapper.findAll&quot;);
    //输出结果
    System.out.println(userList);
    //释放资源
    sqlSession.close();
}
</code></pre>
<h3 id="4-mybatis插入数据">4. MyBatis插入数据</h3>
<blockquote>
<p>MyBatis默认事务不提交，增删改操作无效，需要使用 <code>sqlSession.commit();</code> 提交事务</p>
</blockquote>
<pre><code class="language-xml">&lt;insert id=&quot;save&quot; parameterType=&quot;com.zhiyuan.mybatis.entity.User&quot;&gt;
    insert into user values (#{id},#{name},#{age},#{gender})
&lt;/insert&gt;
</code></pre>
<pre><code class="language-java">@Test
public void test2() throws IOException {
    //读取核心配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);
    //创建会话工厂
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //创建会话对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //执行sql返回结果
    int insert = sqlSession.insert(&quot;userMapper.save&quot;, new User(8, &quot;zhiyuan008&quot;, 26, &quot;male&quot;));
    sqlSession.commit();
    System.out.println(&quot;受影响的行数为&quot;+insert);
    //释放资源
    sqlSession.close();
}
</code></pre>
<h3 id="5-mybatis修改数据">5. Mybatis修改数据</h3>
<pre><code class="language-xml">&lt;update id=&quot;change&quot; parameterType=&quot;com.zhiyuan.mybatis.entity.User&quot;&gt;
    update user set name=#{name}, gender=#{gender} where id=#{id}
&lt;/update&gt;
</code></pre>
<pre><code class="language-java">@Test
public void test3() throws IOException {
    //读取核心配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);
    //创建会话工厂
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //创建会话对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //执行sql返回结果
    int update = sqlSession.update(&quot;userMapper.change&quot;, new User(8, &quot;lisi&quot;, 99, &quot;female&quot;));
    sqlSession.commit();
    System.out.println(&quot;受影响的行数为&quot;+update);
    //释放资源
    sqlSession.close();
}
</code></pre>
<h3 id="6-mybatis删除数据">6. MyBatis删除数据</h3>
<pre><code class="language-xml">&lt;delete id=&quot;delete&quot; parameterType=&quot;java.lang.Integer&quot;&gt;
    delete from user where id=#{id}
&lt;/delete&gt;
</code></pre>
<pre><code class="language-java">@Test
public void test4() throws IOException {
    //读取核心配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);
    //创建会话工厂
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //创建会话对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //执行sql返回结果
    int delete = sqlSession.delete(&quot;userMapper.delete&quot;, 8);
    sqlSession.commit();
    System.out.println(&quot;受影响的行数为&quot;+delete);
    //释放资源
    sqlSession.close();
}
</code></pre>
<h3 id="7-mybatis核心配置文件">7. MyBatis核心配置文件</h3>
<h4 id="1-environments-标签">①. <code>environments</code> 标签</h4>
<ul>
<li>数据库环境的配置，支持多配置</li>
</ul>
<pre><code class="language-xml">&lt;!--指定默认的环境名称--&gt;
&lt;environments default=&quot;development&quot;&gt;
    &lt;!--指定当前环境的名称--&gt;
    &lt;environment id=&quot;development&quot;&gt;
        &lt;!--指定事务管理类型为JDBC--&gt;
        &lt;transactionManager type=&quot;JDBC&quot;/&gt;
        &lt;!--指定当前数据源类型为连接池--&gt;
        &lt;dataSource type=&quot;POOLED&quot;&gt;
            &lt;!--数据源配置的基本参数--&gt;
            &lt;property name=&quot;driver&quot; value=&quot;com.mysql.cj.jdbc.Driver&quot;/&gt;
            &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost/test?serverTimezone=Asia/Shanghai&amp;amp;useUnicode=true&amp;amp;characterEncoding=utf8&amp;amp;useSSL=true&quot;/&gt;
            &lt;property name=&quot;username&quot; value=&quot;root&quot;/&gt;
            &lt;property name=&quot;password&quot; value=&quot;123456&quot;/&gt;
        &lt;/dataSource&gt;
    &lt;/environment&gt;
&lt;/environments&gt;
</code></pre>
<ul>
<li>
<p>事务管理器</p>
<ul>
<li>JDBC</li>
<li>MANAGED</li>
</ul>
</li>
<li>
<p>数据源</p>
<ul>
<li>UNPOOLED：每次被请求时打开连接</li>
<li>POOLED：每次请求时从连接池中获取连接</li>
<li>JNDI：应用容器使用</li>
</ul>
</li>
</ul>
<h4 id="2-mappers-标签">②. <code>mappers</code> 标签</h4>
<ul>
<li>加载映射</li>
</ul>
<pre><code class="language-xml">&lt;mappers&gt;
    &lt;mapper resource=&quot;com/zhiyuan/mapper/UserMapper.xml&quot;/&gt;
&lt;/mappers&gt;
</code></pre>
<ul>
<li>使用相对于类路径的资源引用： <code>&lt;mapper resource=&quot;com/zhiyuan/mapper/UserMapper.xml&quot;&gt;</code></li>
<li>使用完全限定资源定位符：<code>&lt;mapper url=&quot;file:///var/mapper/UserMapper.xml&quot;&gt;</code></li>
<li>使用映射器接口实现类的完全限定类名：<code>&lt;mapper class=&quot;com.zhiyuan.builder.UserMapper&quot;&gt;</code></li>
<li>将包内的映射器接口实现全部注册为映射器：<code>&lt;package name=&quot;com.zhiyuan.builder&quot;&gt;</code></li>
</ul>
<h4 id="3-properties-标签">③. <code>properties</code> 标签</h4>
<ul>
<li>加载外部properties配置文件</li>
</ul>
<pre><code class="language-xml">&lt;properties resource=&quot;jdbc.properties&quot;/&gt;
&lt;!--指定默认的环境名称--&gt;
&lt;environments default=&quot;development&quot;&gt;
    &lt;!--指定当前环境的名称--&gt;
    &lt;environment id=&quot;development&quot;&gt;
        &lt;!--指定事务管理类型为JDBC--&gt;
        &lt;transactionManager type=&quot;JDBC&quot;/&gt;
        &lt;!--指定当前数据源类型为连接池--&gt;
        &lt;dataSource type=&quot;POOLED&quot;&gt;
            &lt;!--数据源配置的基本参数--&gt;
            &lt;property name=&quot;driver&quot; value=&quot;${driverClassName}&quot;/&gt;
            &lt;property name=&quot;url&quot; value=&quot;${jdbcUrl}&quot;/&gt;
            &lt;property name=&quot;username&quot; value=&quot;${username}&quot;/&gt;
            &lt;property name=&quot;password&quot; value=&quot;${password}&quot;/&gt;
        &lt;/dataSource&gt;
    &lt;/environment&gt;
&lt;/environments&gt;
</code></pre>
<h4 id="4-typealiases-标签">④. <code>typeAliases</code> 标签</h4>
<ul>
<li>为指定类型设置别名，方便映射配置</li>
</ul>
<pre><code class="language-xml">&lt;typeAliases&gt;
	&lt;typeAlias type=&quot;com.zhiyuan.mybatis.entity.User&quot; alias=&quot;user&quot;/&gt;
&lt;/typeAliases&gt;
</code></pre>
<ul>
<li>必须按照规定的顺序配置typeAliases标签，否则会报错</li>
</ul>
<blockquote>
<p><code>The content of element type &quot;configuration&quot; must match &quot;(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)&quot;.</code></p>
</blockquote>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;
&lt;mapper namespace=&quot;userMapper&quot;&gt;
    &lt;select id=&quot;findAll&quot; resultType=&quot;user&quot;&gt;
        select * from user
    &lt;/select&gt;
    &lt;insert id=&quot;save&quot; parameterType=&quot;user&quot;&gt;
        insert into user values (#{id},#{name},#{age},#{gender})
    &lt;/insert&gt;
    &lt;update id=&quot;change&quot; parameterType=&quot;user&quot;&gt;
        update user set name=#{name}, gender=#{gender} where id=#{id}
    &lt;/update&gt;
    &lt;delete id=&quot;delete&quot; parameterType=&quot;int&quot;&gt;
        delete from user where id=#{id}
    &lt;/delete&gt;
&lt;/mapper&gt;
</code></pre>
<h3 id="8-mybatis的api">8. MyBatis的API</h3>
<ul>
<li>
<p><code>Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;)</code></p>
<p>读取核心配置文件到IO流</p>
</li>
<li>
<p><code>new SqlSessionFactoryBuilder().build(InputStream is)</code></p>
<p>通过加载核心配置文件创建SqlSessionFactory对象</p>
</li>
<li>
<p><code>SqlSessionFactory.openSession(boolean autoCommit)</code></p>
<p>获取SqlSession对象，给定参数设定是否自动提交事务，不给参数默认不自动提交</p>
</li>
<li>
<p><code>SqlSession对象方法</code></p>
<ul>
<li><code>SqlSession.selectOne(String statement,Object parameter)</code></li>
<li><code>SqlSession.selectList(String statement,Object parameter)</code></li>
<li><code>SqlSession.insert(String statement,Object parameter)</code></li>
<li><code>SqlSession.update(String statement,Object parameter)</code></li>
<li><code>SqlSession.delete(String statement,Object parameter)</code></li>
<li><code>SqlSession.commit()</code></li>
<li><code>SqlSession.rollback()</code></li>
</ul>
</li>
</ul>
<h3 id="9-mybatis的代理开发方式">9. MyBatis的代理开发方式</h3>
<h4 id="1-开发规范">①. 开发规范</h4>
<ul>
<li>Mapper.xml文件中的namespace应该与Mapper接口的全限定名相同</li>
<li>Mapper接口方法名应该和Mapper.xml中定义的每个statement的id相同</li>
<li>Mapper接口方法的输入参数类型应该和Mapper.xml中定义的每个sql的parameterType相同</li>
<li>Mapper接口方法的输出参数类型应该和Mapper.xml中定义的每个sql的resultType相同</li>
</ul>
<h4 id="2-代码实现-2">②. 代码实现</h4>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;
&lt;mapper namespace=&quot;com.zhiyuan.mybatis.dao.UserDao&quot;&gt;
    &lt;select id=&quot;findAll&quot; resultType=&quot;user&quot;&gt;
        select * from user
    &lt;/select&gt;
&lt;/mapper&gt;    
</code></pre>
<pre><code class="language-java">public interface UserDao {
    public abstract List&lt;User&gt; findAll();
}
</code></pre>
<pre><code class="language-java">public class ServiceDemo {
    public static void main(String[] args) throws IOException {
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;));
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List&lt;User&gt; userList = userDao.findAll();
        System.out.println(userList);
    }
}
</code></pre>
<h3 id="10-mybatis映射文件深入">10. MyBatis映射文件深入</h3>
<h4 id="1-动态sql">①. 动态SQL</h4>
<pre><code class="language-java">public interface UserDao {
    public abstract List&lt;User&gt; findAll();
    public abstract List&lt;User&gt; findByIds(List&lt;Integer&gt; list);
    public abstract List&lt;User&gt; findByCondition(User user);
}
</code></pre>
<pre><code class="language-xml">&lt;select id=&quot;findByIds&quot; parameterType=&quot;list&quot; resultType=&quot;user&quot;&gt;
    select * from user
    &lt;where&gt;
        &lt;foreach collection=&quot;list&quot; open=&quot;id in(&quot; close=&quot;)&quot; item=&quot;id&quot; separator=&quot;,&quot;&gt;
            #{id}
        &lt;/foreach&gt;
    &lt;/where&gt;
&lt;/select&gt;
&lt;select id=&quot;findByCondition&quot; parameterType=&quot;user&quot; resultType=&quot;user&quot;&gt;
    select * from user
    &lt;where&gt;
        &lt;if test=&quot;id!=0&quot;&gt;
            and id=#{id}
        &lt;/if&gt;
        &lt;if test=&quot;name!=null&quot;&gt;
            and name=#{name}
        &lt;/if&gt;
        &lt;if test=&quot;age!=0&quot;&gt;
            and age=#{age}
        &lt;/if&gt;
        &lt;if test=&quot;gender!=null&quot;&gt;
            and gender=#{gender}
        &lt;/if&gt;
    &lt;/where&gt;
&lt;/select&gt;
</code></pre>
<h4 id="2-sql语句的抽取">②. SQL语句的抽取</h4>
<pre><code class="language-xml">&lt;sql id=&quot;selectUser&quot;&gt;select * from user&lt;/sql&gt;
&lt;select id=&quot;findAll&quot; resultType=&quot;user&quot;&gt;
    &lt;include refid=&quot;selectUser&quot;/&gt;
&lt;/select&gt;
</code></pre>
<h4 id="3-小结">③. 小结</h4>
<ul>
<li><code>&lt;select&gt;</code>：查询数据</li>
<li><code>&lt;insert&gt;</code>：插入数据</li>
<li><code>&lt;update&gt;</code>：修改数据</li>
<li><code>&lt;delete&gt;</code>：删除数据</li>
<li><code>&lt;where&gt;</code>：条件</li>
<li><code>&lt;if&gt;</code>：判断</li>
<li><code>&lt;foreach&gt;</code>：循环</li>
<li><code>&lt;sql&gt;</code>：sql抽取</li>
</ul>
<h3 id="11-mybatis核心文件深入">11. MyBatis核心文件深入</h3>
<h4 id="1-typehandlers-标签">①. <code>typeHandlers</code> 标签</h4>
<blockquote>
<p>将结果集中的值转换成指定Java类型</p>
<ul>
<li><code>BooleanTypeHandler </code></li>
<li><code>ByteTypeHandler</code></li>
<li><code>ShortTypeHandler</code></li>
<li><code>IntegerTypeHandler</code></li>
<li><code>LongTypeHandler</code></li>
</ul>
</blockquote>
<ul>
<li>开发步骤
<ul>
<li>定义转换类继承自 <code>BaseTypeHandler&lt;T&gt;</code></li>
<li>实现方法，其中 <code>setNonNullParameter</code> 是java程序设置数据到数据库的回调方法，<code>getNullableResult</code>是查询时mysql字符串类型转为Java的Type类型的方法</li>
<li>在MyBatis核心配置文件中进行注册</li>
<li>测试转换是否正确</li>
</ul>
</li>
</ul>
<pre><code class="language-java">public class DateTypeHandler extends BaseTypeHandler&lt;Date&gt; {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        long time = parameter.getTime();
        ps.setLong(i,time);
    }

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return new Date(rs.getLong(columnName));
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return new Date(rs.getLong(columnIndex));
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return new Date(cs.getLong(columnIndex));
    }
}
</code></pre>
<pre><code class="language-xml">&lt;typeHandlers&gt;
    &lt;typeHandler handler=&quot;com.zhiyuan.mybatis.handler.DateTypeHandler&quot;/&gt;
&lt;/typeHandlers&gt;
</code></pre>
<h4 id="2-plugins-标签">②. <code>plugins</code> 标签</h4>
<ul>
<li>MyBatis可以使用第三方插件来对功能进行扩展，分页助手PageHelper是将分页的复杂操作进行封装，使用简单的方式即可获得分页的相关数据</li>
<li>开发步骤：
<ul>
<li>导入通用PageHelper的坐标</li>
<li>在MyBatis核心配置文件中配置PageHelper</li>
<li>测试分页数据获取</li>
</ul>
</li>
<li>导入依赖</li>
</ul>
<pre><code class="language-xml">&lt;!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper --&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.github.pagehelper&lt;/groupId&gt;
  &lt;artifactId&gt;pagehelper&lt;/artifactId&gt;
  &lt;version&gt;5.2.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser --&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.github.jsqlparser&lt;/groupId&gt;
  &lt;artifactId&gt;jsqlparser&lt;/artifactId&gt;
  &lt;version&gt;3.2&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<ul>
<li>注册分页插件</li>
</ul>
<pre><code class="language-xml">&lt;!--注册分页插件--&gt;
&lt;plugins&gt;
    &lt;plugin interceptor=&quot;com.github.pagehelper.PageInterceptor&quot;&gt;
        &lt;!--pagehelper4.0之后不需要配置此项，否则会出错--&gt;
        &lt;property name=&quot;dialect&quot; value=&quot;mysql&quot;/&gt;
    &lt;/plugin&gt;
&lt;/plugins&gt;
</code></pre>
<ul>
<li>代码实现</li>
</ul>
<pre><code class="language-java">@Test
public void test5() throws IOException {
    //读取核心配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);
    //创建会话工厂
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //创建会话对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    PageHelper.startPage(1,3);
    List&lt;User&gt; userList = userDao.findAll();
    System.out.println(userList);
    PageInfo&lt;User&gt; userPageInfo = new PageInfo&lt;&gt;(userList);
    System.out.println(&quot;当前页：&quot; + userPageInfo.getPageNum());
    System.out.println(&quot;每页显示条数：&quot; + userPageInfo.getPageSize());
    System.out.println(&quot;总条数：&quot; + userPageInfo.getTotal());
    System.out.println(&quot;总页数：&quot; + userPageInfo.getPages());
    System.out.println(&quot;上一页：&quot; + userPageInfo.getPrePage());
    System.out.println(&quot;下一页：&quot; + userPageInfo.getNextPage());
    System.out.println(&quot;是否是首页：&quot; + userPageInfo.isIsFirstPage());
    System.out.println(&quot;是否是尾页：&quot; + userPageInfo.isIsLastPage());
    sqlSession.close();
}
</code></pre>
<h3 id="12-mybatis的多表操作">12. MyBatis的多表操作</h3>
<h4 id="1-一对一查询模型">①. 一对一查询模型</h4>
<ul>
<li>根据指定订单号查询订单和用户信息</li>
</ul>
<h5 id="创建订单order对象">创建订单Order对象</h5>
<ul>
<li>
<pre><code class="language-java">package com.zhiyuan.mybatis.entity;

import java.util.Date;

public class Order {
    private int id;
    private String ordertime;
    private double total;
    private User user;

    public Order() {}

    public Order(int id, String ordertime, double total, User user) {
        this.id = id;
        this.ordertime = ordertime;
        this.total = total;
        this.user = user;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getOrdertime() {
        return ordertime;
    }

    public void setOrdertime(String ordertime) {
        this.ordertime = ordertime;
    }

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer(&quot;Order{&quot;);
        sb.append(&quot;id=&quot;).append(id);
        sb.append(&quot;, ordertime=&quot;).append(ordertime);
        sb.append(&quot;, total=&quot;).append(total);
        sb.append(&quot;, user=&quot;).append(user);
        sb.append('}');
        return sb.toString();
    }
}
</code></pre>
</li>
</ul>
<h5 id="配置映射文件">配置映射文件</h5>
<ul>
<li>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;
&lt;mapper namespace=&quot;com.zhiyuan.mybatis.dao.OrderDao&quot;&gt;
    &lt;resultMap id=&quot;orderMap&quot; type=&quot;order&quot;&gt;
        &lt;id column=&quot;oid&quot; property=&quot;id&quot;/&gt;
        &lt;result column=&quot;ordertime&quot; property=&quot;ordertime&quot;/&gt;
        &lt;result column=&quot;total&quot; property=&quot;total&quot;/&gt;
        &lt;result column=&quot;uid&quot; property=&quot;user.id&quot;/&gt;
        &lt;result column=&quot;name&quot; property=&quot;user.name&quot;/&gt;
        &lt;result column=&quot;age&quot; property=&quot;user.age&quot;/&gt;
        &lt;result column=&quot;gender&quot; property=&quot;user.gender&quot;/&gt;
    &lt;/resultMap&gt;
    &lt;select id=&quot;findAll&quot; resultMap=&quot;orderMap&quot;&gt;
        select o.id oid,u.id uid,ordertime,total,name,age,gender from orders o,user u where o.uid=u.id
    &lt;/select&gt;
&lt;/mapper&gt;
</code></pre>
</li>
</ul>
<h5 id="优化配置文件">优化配置文件</h5>
<ul>
<li>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;
&lt;mapper namespace=&quot;com.zhiyuan.mybatis.dao.OrderDao&quot;&gt;
    &lt;resultMap id=&quot;orderMap&quot; type=&quot;order&quot;&gt;
        &lt;id column=&quot;oid&quot; property=&quot;id&quot;/&gt;
        &lt;result column=&quot;ordertime&quot; property=&quot;ordertime&quot;/&gt;
        &lt;result column=&quot;total&quot; property=&quot;total&quot;/&gt;
        &lt;association property=&quot;user&quot; javaType=&quot;user&quot;&gt;
            &lt;id column=&quot;uid&quot; property=&quot;id&quot;/&gt;
            &lt;result column=&quot;name&quot; property=&quot;name&quot;/&gt;
            &lt;result column=&quot;age&quot; property=&quot;age&quot;/&gt;
            &lt;result column=&quot;gender&quot; property=&quot;gender&quot;/&gt;
        &lt;/association&gt;
    &lt;/resultMap&gt;
    &lt;select id=&quot;findAll&quot; resultMap=&quot;orderMap&quot;&gt;
        select o.id oid,u.id uid,ordertime,total,name,age,gender from orders o,user u where o.uid=u.id
    &lt;/select&gt;
&lt;/mapper&gt;
</code></pre>
</li>
</ul>
<h4 id="2-一对多查询模型">②. 一对多查询模型</h4>
<ul>
<li>根据用户id获取用户所有订单信息</li>
</ul>
<h5 id="创建用户user对象">创建用户User对象</h5>
<pre><code class="language-java">package com.zhiyuan.mybatis.entity;

import java.util.List;
public class User {
    private int id;
    private String name;
    private int age;
    private String gender;

    private List&lt;Order&gt; orderList;

    public User() {}

    public User(int id, String name, int age, String gender) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public List&lt;Order&gt; getOrderList() {
        return orderList;
    }

    public void setOrderList(List&lt;Order&gt; orderList) {
        this.orderList = orderList;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer(&quot;User{&quot;);
        sb.append(&quot;id=&quot;).append(id);
        sb.append(&quot;, name='&quot;).append(name).append('\'');
        sb.append(&quot;, age=&quot;).append(age);
        sb.append(&quot;, gender='&quot;).append(gender).append('\'');
        sb.append(&quot;, orderList=&quot;).append(orderList);
        sb.append('}');
        return sb.toString();
    }
}
</code></pre>
<h5 id="配置usermapperxml">配置UserMapper.xml</h5>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;
&lt;mapper namespace=&quot;com.zhiyuan.mybatis.dao.UserDao&quot;&gt;
    &lt;sql id=&quot;selectUser&quot;&gt;select * from user&lt;/sql&gt;
    &lt;resultMap id=&quot;userMap&quot; type=&quot;user&quot;&gt;
        &lt;id column=&quot;uid&quot; property=&quot;id&quot;/&gt;
        &lt;result column=&quot;name&quot; property=&quot;name&quot;/&gt;
        &lt;result column=&quot;age&quot; property=&quot;age&quot;/&gt;
        &lt;result column=&quot;gender&quot; property=&quot;gender&quot;/&gt;
        &lt;collection property=&quot;orderList&quot; ofType=&quot;order&quot;&gt;
            &lt;id column=&quot;oid&quot; property=&quot;id&quot;/&gt;
            &lt;result column=&quot;ordertime&quot; property=&quot;ordertime&quot;/&gt;
            &lt;result column=&quot;total&quot; property=&quot;total&quot;/&gt;
        &lt;/collection&gt;
    &lt;/resultMap&gt;
    &lt;select id=&quot;findAllOrder&quot; resultMap=&quot;userMap&quot;&gt;
        select o.id oid,u.id uid,ordertime,total,name,age,gender from orders o,user u where o.uid=u.id
    &lt;/select&gt;
&lt;/mapper&gt;
</code></pre>
<h5 id="测试结果">测试结果</h5>
<pre><code class="language-java">@Test
public void test7() throws IOException {
    //读取核心配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);
    //创建会话工厂
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //创建会话对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    List&lt;Order&gt; allOrder = userDao.findAllOrder();
    System.out.println(allOrder);
}
</code></pre>
<h4 id="3-多对多查询模型">③. 多对多查询模型</h4>
<ul>
<li>查询一个用户对应的多个角色</li>
</ul>
<h4 id="4-小结">④. 小结</h4>
<ul>
<li>MyBatis多表配置方式
<ul>
<li>一对一配置：使用 <code>&lt;resultMap&gt;</code> 做配置</li>
<li>一对多配置：使用 <code>&lt;resultMap&gt;+&lt;collection&gt;</code> 做配置</li>
<li>多对多配置：使用 <code>&lt;resultMap&gt;+&lt;collection&gt;</code> 做配置</li>
</ul>
</li>
</ul>
<h3 id="13-mybatis的注解开发">13. MyBatis的注解开发</h3>
<h4 id="1-insert-实现插入">①. <code>@Insert</code> 实现插入</h4>
<h4 id="2-update-实现更新">②. <code>@Update</code> 实现更新</h4>
<h4 id="3-delete-实现删除">③. <code>@Delete</code> 实现删除</h4>
<h4 id="4-select-实现查询">④. <code>@Select</code> 实现查询</h4>
<h4 id="5-result-实现结果集封装">⑤. <code>@Result</code> 实现结果集封装</h4>
<h4 id="6-results-可以与-result-一起使用封装多个结果集">⑥. <code>@Results</code> 可以与 <code>@Result</code> 一起使用，封装多个结果集</h4>
<h4 id="7-one-实现一对一结果集封装">⑦. <code>@One</code> 实现一对一结果集封装</h4>
<h4 id="8-many-实现一对多结果集封装">⑧. <code>@Many</code> 实现一对多结果集封装</h4>
<h3 id="14-导出资源失败问题">14. 导出资源失败问题</h3>
<pre><code class="language-xml">&lt;build&gt;
    &lt;resources&gt;
        &lt;resource&gt;
            &lt;directory&gt;src/main/resources&lt;/directory&gt;
            &lt;includes&gt;
                &lt;include&gt;**/*.properties&lt;/include&gt;
                &lt;include&gt;**/*.xml&lt;/include&gt;
            &lt;/includes&gt;
            &lt;filtering&gt;false&lt;/filtering&gt;
        &lt;/resource&gt;

        &lt;resource&gt;
            &lt;directory&gt;src/main/java&lt;/directory&gt;
            &lt;includes&gt;
                &lt;include&gt;**/*.properties&lt;/include&gt;
                &lt;include&gt;**/*.xml&lt;/include&gt;
            &lt;/includes&gt;
            &lt;filtering&gt;false&lt;/filtering&gt;
        &lt;/resource&gt;
    &lt;/resources&gt;
&lt;/build&gt;
</code></pre>
<h3 id="15-数据库和实体类映射业内共识">15. 数据库和实体类映射业内共识</h3>
<ul>
<li>表名小写：<code>User.java</code> --- <code>user</code>         <code>EduUser</code> --- <code>edu_user</code></li>
<li>《阿里Java开发规范》中的约定
<ul>
<li>不得使用大写字母，不得连写两个单词；</li>
<li>表必备三字段：id, gmt_create, gmt_modified；
<ul>
<li>其中 id 必为主键，类型为 unsigned bigint、单表时自增、步长为 1；分表时改为从TDDL Sequence 取值，确保分表之间的全局唯一。gmt_create, gmt_modified 的类型均为date_time 类型；</li>
</ul>
</li>
<li>用尽量少的存储空间来存 数一个字段的数据；
<ul>
<li>能用int的就不用char或者varchar；</li>
<li>能用tinyint的就不用int；</li>
<li>能用varchar(20)的就不用varchar(255)；</li>
<li>时间戳字段尽量用int型，如gmt_create:表示从 ‘1970-01-01 08:00:00’ 开始的int秒数，采用英文单词的过去式；gmtCreated:表示datetime类型的时间，即形如 '1980-01-01 00:00:00’的时间串，Java中对应的类型为Timestamp</li>
</ul>
</li>
<li>不得使用外键与级联，一切外键概念必须在应用层解决。
<ul>
<li>说明：（概念解释）学生表中的 student_id 是主键，那么成绩表中的 student_id 则为外键。如果更新学生表中的 student_id，同时触发成绩表中的 student_id 更新，则为级联更新。外键与级联更新适用于单机低并发，不适合分布式、高并发集群；级联更新是强阻塞，存在数据库更新风暴的风险；外键影响数据库的插入速度。</li>
</ul>
</li>
<li>禁止使用存储过程，存储过程难以调试和扩展，更没有移植性。</li>
</ul>
</li>
</ul>
<h3 id="16-mybatis的逆向创建pojo">16. MyBatis的逆向创建POJO</h3>
<pre><code class="language-xml">&lt;!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.mybatis.generator&lt;/groupId&gt;
    &lt;artifactId&gt;mybatis-generator-core&lt;/artifactId&gt;
    &lt;version&gt;1.3.7&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<p>几乎没人用了</p>
<h2 id="五-ssm框架整合">五、SSM框架整合</h2>
<h3 id="1-原始整合方式">1. 原始整合方式</h3>
<h4 id="1-导入pomxml依赖">①. 导入pom.xml依赖</h4>
<pre><code class="language-xml">&lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;junit&lt;/groupId&gt;
      &lt;artifactId&gt;junit&lt;/artifactId&gt;
      &lt;version&gt;4.11&lt;/version&gt;
      &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
      &lt;version&gt;5.2.1.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
      &lt;version&gt;5.2.1.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mybatis&lt;/groupId&gt;
      &lt;artifactId&gt;mybatis&lt;/artifactId&gt;
      &lt;version&gt;3.4.6&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mybatis&lt;/groupId&gt;
      &lt;artifactId&gt;mybatis-spring&lt;/artifactId&gt;
      &lt;version&gt;2.0.5&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.aspectj&lt;/groupId&gt;
      &lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt;
      &lt;version&gt;1.9.6&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.mchange&lt;/groupId&gt;
      &lt;artifactId&gt;c3p0&lt;/artifactId&gt;
      &lt;version&gt;0.9.5.2&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-tx&lt;/artifactId&gt;
      &lt;version&gt;5.2.1.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
      &lt;version&gt;5.2.1.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
      &lt;version&gt;5.2.1.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
      &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
      &lt;version&gt;4.0.1&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt;
      &lt;artifactId&gt;javax.servlet.jsp-api&lt;/artifactId&gt;
      &lt;version&gt;2.3.3&lt;/version&gt;
      &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;mysql&lt;/groupId&gt;
      &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
      &lt;version&gt;8.0.21&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt;
      &lt;artifactId&gt;javax.servlet.jsp.jstl-api&lt;/artifactId&gt;
      &lt;version&gt;1.2.2&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;taglibs&lt;/groupId&gt;
      &lt;artifactId&gt;standard&lt;/artifactId&gt;
      &lt;version&gt;1.1.2&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;log4j&lt;/groupId&gt;
      &lt;artifactId&gt;log4j&lt;/artifactId&gt;
      &lt;version&gt;1.2.17&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;commons-logging&lt;/groupId&gt;
      &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
      &lt;version&gt;1.2&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;commons-io&lt;/groupId&gt;
      &lt;artifactId&gt;commons-io&lt;/artifactId&gt;
      &lt;version&gt;2.6&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;commons-fileupload&lt;/groupId&gt;
      &lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt;
      &lt;version&gt;1.3.1&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
</code></pre>
<h4 id="2-创建实体类accountjava">②. 创建实体类Account.java</h4>
<h4 id="3-编写accountmapperjava">③. 编写AccountMapper.java</h4>
<pre><code class="language-java">public interface AccountMapper {
    public abstract void add(Account account);
    public abstract List&lt;Account&gt; findAll();
}
</code></pre>
<h4 id="4-编写accountservicejava">④. 编写AccountService.java</h4>
<pre><code class="language-java">public interface AccountService {
    public abstract void add(Account account);
    public abstract List&lt;Account&gt; findAll();
}
</code></pre>
<h4 id="5-编写accountserviceimpljava">⑤. 编写AccountServiceImpl.java</h4>
<pre><code class="language-java">@Service(&quot;accountService&quot;)
public class AccountServiceImpl implements AccountService {
    private static AccountMapper accountMapper = MyUtils.getSqlSession().getMapper(AccountMapper.class);
    @Override
    public void add(Account account) {
        accountMapper.add(account);
    }

    @Override
    public List&lt;Account&gt; findAll() {
        return accountMapper.findAll();
    }
}
</code></pre>
<h4 id="6-编写工具类myutilsjava">⑥. 编写工具类MyUtils.java</h4>
<pre><code class="language-java">public class MyUtils {
    private static SqlSession sqlSession;
    private MyUtils(){}
    static{
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);
            sqlSession = new SqlSessionFactoryBuilder().build(resourceAsStream).openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSession;
    }
}
</code></pre>
<h4 id="7-编写accountcontrollerjava">⑦. 编写AccountController.java</h4>
<pre><code class="language-java">@RestController
@RequestMapping(&quot;/account&quot;)
public class AccountController {
    @Autowired
    private AccountService accountService;
    @PostMapping(value = &quot;/add&quot;,produces = &quot;text/html;charset=utf-8&quot;)
    @ResponseBody
    public String add(Account account){
        accountService.add(account);
        return &quot;保存成功&quot;;
    }

    @RequestMapping(&quot;/findAll&quot;)
    public ModelAndView findAll(){
        List&lt;Account&gt; accountList = accountService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject(&quot;accountList&quot;,accountList);
        modelAndView.setViewName(&quot;accountlist&quot;);
        return modelAndView;
    }
}
</code></pre>
<h4 id="8-配置springspringmvcmybatis">⑧. 配置Spring+SpringMVC+MyBatis</h4>
<blockquote>
<h5 id="springapplicationcontextxml">Spring：applicationContext.xml</h5>
</blockquote>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       &quot;&gt;
    &lt;!--配置组件扫描--&gt;
    &lt;context:component-scan base-package=&quot;com.zhiyuan.ssm&quot;&gt;
        &lt;!--取消对Controller注解的扫描，交由SpringMVC来管理--&gt;
        &lt;context:exclude-filter type=&quot;annotation&quot; expression=&quot;org.springframework.stereotype.Controller&quot;/&gt;
    &lt;/context:component-scan&gt;
&lt;/beans&gt;
</code></pre>
<blockquote>
<h5 id="springmvcspring-mvcxml">SpringMVC：spring-mvc.xml</h5>
</blockquote>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xmlns:mvc=&quot;http://www.springframework.org/schema/mvc&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       &quot;&gt;
    &lt;!--配置组件扫描，主要扫描Controller--&gt;
    &lt;context:component-scan base-package=&quot;com.zhiyuan.ssm.controller&quot;/&gt;
    &lt;!--配置mvc注解驱动--&gt;
    &lt;mvc:annotation-driven/&gt;
    &lt;!--交由tomcat寻找静态资源--&gt;
    &lt;mvc:default-servlet-handler/&gt;
    &lt;!--配置内部资源视图解析器--&gt;
    &lt;bean id=&quot;resourceViewResolver&quot; class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
        &lt;property name=&quot;prefix&quot; value=&quot;/pages/&quot;/&gt;
        &lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<blockquote>
<h5 id="mybatisaccountmapperxml-sqlmapconfigxml">MyBatis：AccountMapper.xml + SqlMapConfig.xml</h5>
</blockquote>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE mapper
        PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;
        &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;
&lt;mapper namespace=&quot;com.zhiyuan.ssm.mapper.AccountMapper&quot;&gt;
    &lt;insert id=&quot;add&quot; parameterType=&quot;account&quot;&gt;
        insert into account (name,balance) values (#{name},#{balance})
    &lt;/insert&gt;
    &lt;select id=&quot;findAll&quot; resultType=&quot;account&quot;&gt;
        select * from account
    &lt;/select&gt;
&lt;/mapper&gt;
</code></pre>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE configuration
        PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot;
        &quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;&gt;
&lt;configuration&gt;
    &lt;!--引入数据库配置文件--&gt;
    &lt;properties resource=&quot;jdbc.properties&quot;/&gt;
    &lt;!--定义别名--&gt;
    &lt;typeAliases&gt;
        &lt;!--&lt;typeAlias type=&quot;com.zhiyuan.ssm.entity.Account&quot; alias=&quot;account&quot;/&gt;--&gt;
        &lt;package name=&quot;com.zhiyuan.ssm.entity&quot;/&gt;
    &lt;/typeAliases&gt;
    &lt;!--配置环境--&gt;
    &lt;environments default=&quot;developement&quot;&gt;
        &lt;environment id=&quot;developement&quot;&gt;
            &lt;transactionManager type=&quot;JDBC&quot;/&gt;
            &lt;dataSource type=&quot;POOLED&quot;&gt;
                &lt;property name=&quot;driver&quot; value=&quot;${driverClassName}&quot;/&gt;
                &lt;property name=&quot;url&quot; value=&quot;${jdbcUrl}&quot;/&gt;
                &lt;property name=&quot;username&quot; value=&quot;${dbusername}&quot;/&gt;
                &lt;property name=&quot;password&quot; value=&quot;${dbpassword}&quot;/&gt;
            &lt;/dataSource&gt;
        &lt;/environment&gt;
    &lt;/environments&gt;
    &lt;!--加载映射--&gt;
    &lt;mappers&gt;
        &lt;mapper resource=&quot;com\zhiyuan\ssm\mapper\AccountMapper.xml&quot;/&gt;
    &lt;/mappers&gt;
&lt;/configuration&gt;
</code></pre>
<h3 id="2-优化整合方式">2. 优化整合方式</h3>
<h4 id="1-导入pomxml依赖-2">①. 导入pom.xml依赖</h4>
<pre><code class="language-xml">&lt;dependency&gt;
  &lt;groupId&gt;org.springframework&lt;/groupId&gt;
  &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
  &lt;version&gt;5.2.1.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
      &lt;groupId&gt;com.mchange&lt;/groupId&gt;
      &lt;artifactId&gt;c3p0&lt;/artifactId&gt;
      &lt;version&gt;0.9.5.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
      &lt;groupId&gt;org.mybatis&lt;/groupId&gt;
      &lt;artifactId&gt;mybatis-spring&lt;/artifactId&gt;
      &lt;version&gt;2.0.5&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<h4 id="2-将sqlsessionfactory配置到spring容器中">②. 将SqlSessionFactory配置到Spring容器中</h4>
<pre><code class="language-xml">&lt;!--加载配置文件--&gt;
&lt;context:property-placeholder location=&quot;classpath:jdbc.properties&quot;/&gt;
&lt;!--配置数据库连接池信息--&gt;
&lt;bean id=&quot;dataSource&quot; class=&quot;com.mchange.v2.c3p0.ComboPooledDataSource&quot;&gt;
    &lt;property name=&quot;driverClass&quot; value=&quot;${driverClassName}&quot;/&gt;
    &lt;property name=&quot;jdbcUrl&quot; value=&quot;${jdbcUrl}&quot;/&gt;
    &lt;property name=&quot;user&quot; value=&quot;${dbusername}&quot;/&gt;
    &lt;property name=&quot;password&quot; value=&quot;${dbpassword}&quot;/&gt;
&lt;/bean&gt;
&lt;!--配置SqlSessionFactory--&gt;
&lt;bean id=&quot;sqlSessionFactory&quot; class=&quot;org.mybatis.spring.SqlSessionFactoryBean&quot;&gt;
    &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;
    &lt;!--引入其他配置信息--&gt;
    &lt;property name=&quot;configLocation&quot; value=&quot;classpath:SqlMapConfig-Spring.xml&quot;/&gt;
&lt;/bean&gt;
&lt;!--扫描所有mapper创建对象--&gt;
&lt;bean class=&quot;org.mybatis.spring.mapper.MapperScannerConfigurer&quot;&gt;
    &lt;property name=&quot;basePackage&quot; value=&quot;com.zhiyuan.ssm.mapper&quot;/&gt;
&lt;/bean&gt;
</code></pre>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE configuration
        PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot;
        &quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;&gt;
&lt;configuration&gt;
    &lt;!--引入数据库配置文件--&gt;
    &lt;properties resource=&quot;jdbc.properties&quot;/&gt;
    &lt;!--定义别名--&gt;
    &lt;typeAliases&gt;
        &lt;!--&lt;typeAlias type=&quot;com.zhiyuan.ssm.entity.Account&quot; alias=&quot;account&quot;/&gt;--&gt;
        &lt;package name=&quot;com.zhiyuan.ssm.entity&quot;/&gt;
    &lt;/typeAliases&gt;
    &lt;!--加载映射--&gt;
    &lt;mappers&gt;
        &lt;mapper resource=&quot;com\zhiyuan\ssm\mapper\AccountMapper.xml&quot;/&gt;
    &lt;/mappers&gt;
&lt;/configuration&gt;
</code></pre>
<h4 id="3-书写accountcontrollerjava">③. 书写AccountController.java</h4>
<pre><code class="language-java">@Service(&quot;accountService&quot;)
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Override
    public void add(Account account) {
        accountMapper.add(account);
    }

    @Override
    public List&lt;Account&gt; findAll() {
        return accountMapper.findAll();
    }
}
</code></pre>
<h4 id="4-声明式事务控制">④. 声明式事务控制</h4>
<pre><code class="language-xml">&lt;!--配置平台事务管理对象--&gt;
&lt;bean id=&quot;transactionManager&quot; class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot;&gt;
    &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;
&lt;/bean&gt;
&lt;!--配置事务增强--&gt;
&lt;tx:advice id=&quot;txAdvice&quot;&gt;
    &lt;tx:attributes&gt;
        &lt;tx:method name=&quot;*&quot;/&gt;
    &lt;/tx:attributes&gt;
&lt;/tx:advice&gt;
&lt;!--事务的织入--&gt;
&lt;aop:config&gt;
    &lt;aop:advisor advice-ref=&quot;txAdvice&quot; pointcut=&quot;execution(* com.zhiyuan.ssm.service.impl.*.*(..))&quot;/&gt;
&lt;/aop:config&gt;
</code></pre>
<h2 id="六-分布式框架">六、分布式框架</h2>
<blockquote>
<p>软件架构的发展过程：<code>单体架构</code> --- <code>垂直架构</code> --- <code>SOA架构</code> --- <code>微服务架构</code></p>
<h4 id="单体架构">单体架构</h4>
<ul>
<li>特点：全部功能几种在一个项目内（All in one）</li>
<li>优点：架构简单，前期开发成本低，开发周期短，适合小型项目</li>
<li>缺点：
<ul>
<li>全部功能集成在一个工程中，对于代行项目不宜开发、扩展和维护</li>
<li>技术栈受限，只能用一种语言开发</li>
<li>系统性能扩展只能通过扩展集群节点，成本高</li>
</ul>
</li>
</ul>
<h4 id="垂直架构">垂直架构</h4>
<ul>
<li>特点：按照业务进行分割，形成小的单体项目</li>
<li>优点：技术栈可扩展</li>
<li>缺点：
<ul>
<li>功能集中在一个项目中，不利于开发、扩展和维护</li>
<li>系统扩张只能通过集群方式</li>
<li>项目之间功能冗杂、数据冗余、耦合性强</li>
</ul>
</li>
</ul>
<h4 id="soa架构">SOA架构</h4>
<ul>
<li>特点：将重复功能或模块抽取成组件的形式，对外提供服务，在项目与服务之间使用ESB（企业服务总线）的形式作为通信的桥梁</li>
<li>优点：
<ul>
<li>重复功能或模块抽取为服务，提高开发效率</li>
<li>可重用性高，可维护性高</li>
</ul>
</li>
<li>缺点：
<ul>
<li>各系统之间有义务不同，很难确认功能或模块是重复的</li>
<li>抽取服务的粒度大</li>
<li>系统和服务之间耦合度高</li>
</ul>
</li>
</ul>
<h4 id="微服务架构">微服务架构</h4>
<ul>
<li>特点：将系统服务层完全独立出来，抽取为一个个的微服务，抽取的粒度更细，遵循单一原则，采用轻量级框架协议传输</li>
<li>优点：
<ul>
<li>服务拆分粒度更细，有利于提高开发效率</li>
<li>可以针对不同服务指定对应的优化方案</li>
<li>适用于互联网时代，产品迭代周期更短</li>
</ul>
</li>
<li>缺点：
<ul>
<li>粒度太大导致服务太多，维护成本高</li>
<li>分布式系统开发的技术成本高，对团队的挑战大</li>
</ul>
</li>
</ul>
</blockquote>
<h3 id="1-apache-dubbo">1. Apache Dubbo</h3>
<blockquote>
<p>Apache Dubbo是一款高性能的Java RPC框架，其前身是阿里巴巴公司开源的一个高性能、轻量级的开源Java RPC框架，可以和Spring框架无缝集成。</p>
<p>RPC：remote procedure call（远程过程调用）</p>
<p>官网：https://dubbo.apache.org/zh/</p>
<p>Apache Dubbo提供了三大核心能力：</p>
<ul>
<li>面向接口的远程方法调用</li>
<li>智能容错和负载均衡</li>
<li>服务自动注册和发现</li>
</ul>
</blockquote>
<h2 id="七-vue学习">七、Vue学习</h2>
<h3 id="1-简介">1. 简介</h3>
<blockquote>
<p><code>Vue</code> 读音与View类似，是一套用于构建用户界面的 <code>渐进式框架</code> ，与其他框架不同的是，Vue被设计为可以自定向上逐层应用，Vue的和辛苦只关注视图层，不仅易上手，还便于与第三方库或既有项目整合，另一方面，当与现代化的工具链以及各种支持类库结合使用时，Vue也完全能够为复杂的单页应用提供驱动</p>
<ul>
<li>渐进式：可以选择性的使用该框架中的一个或一些组件，这些组件的使用也不需要将框架全部组件都应用，而且用了这些组件也不要求你的系统全部都使用该框架</li>
<li>前端主流框架
<ul>
<li>Vue.js</li>
<li>React.js</li>
<li>AngularJS</li>
</ul>
</li>
<li>官网：https://cn.vuejs.org/</li>
</ul>
</blockquote>
<h3 id="2-搭建示例工程">2. 搭建示例工程</h3>
<ul>
<li>Vue的使用方式
<ul>
<li>可以引用在线的Vue.js</li>
<li>可以离线下载Vue.js</li>
<li>npm包资源管理器，可以下载Vue.js</li>
</ul>
</li>
<li>步骤
<ul>
<li><code>npm init -y</code>：初始化</li>
<li><code>npm install vue --save </code>：局部安装vue模块</li>
</ul>
</li>
</ul>
<h3 id="3-演示双向绑定与事件处理">3. 演示双向绑定与事件处理</h3>
<h4 id="1-插值引用-key">①. 插值引用 <code>{{key}}</code></h4>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;第一课&lt;/title&gt;
    &lt;script src=&quot;node_modules/vue/dist/vue.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;
        &lt;h2&gt;{{name}}学Vue&lt;/h2&gt;
    &lt;/div&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        var app = new Vue({
           el:&quot;#app&quot;,
           data:{
               name:&quot;絷缘&quot;
           }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h4 id="2-双向绑定-v-model">②. 双向绑定 <code>v-model</code></h4>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;第一课&lt;/title&gt;
    &lt;script src=&quot;node_modules/vue/dist/vue.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;
        &lt;input type=&quot;text&quot; v-model=&quot;day&quot;/&gt;
        &lt;h2&gt;{{name}}学Vue，学了{{day}}天&lt;/h2&gt;
    &lt;/div&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        var app = new Vue({
           el:&quot;#app&quot;,
           data:{
               name:&quot;絷缘&quot;,
               day:20
           }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h4 id="3-事件处理-v-on事件">③. 事件处理 <code>v-on:事件</code></h4>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;第一课&lt;/title&gt;
    &lt;script src=&quot;node_modules/vue/dist/vue.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;
        &lt;input type=&quot;text&quot; v-model=&quot;day&quot;/&gt;
        &lt;button v-on:click=&quot;day++&quot;&gt;点我加一&lt;/button&gt;
        &lt;h2&gt;{{name}}学Vue，学了{{day}}天&lt;/h2&gt;
    &lt;/div&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        var app = new Vue({
           el:&quot;#app&quot;,
           data:{
               name:&quot;絷缘&quot;,
               day:20
           }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3 id="4-vue的生命周期以及钩子函数">4. Vue的生命周期以及钩子函数</h3>
<h4 id="1-生命周期">①. 生命周期</h4>
<ul>
<li>创建实例：每个Vue应用都是通过Vue函数创建一个新的Vue实例开始的</li>
</ul>
<pre><code class="language-js">var app = new Vue({
	//在构造函数中传入一个对象，并在对象中声明各种Vue所需数据和方法	
});
</code></pre>
<ul>
<li>装载模板：每个Vue实例都需要关联一段html，Vue会基于当前模板进行视图渲染，关联模板通过 <code>el</code> 实现</li>
</ul>
<pre><code class="language-js">var app = new Vue({
    //这样Vue就与id为app的元素关联上了，Vue就可以基于id为app的元素进行渲染数据了
   el:&quot;#app&quot; 
});
</code></pre>
<ul>
<li>渲染模板：当Vue实例被创建时，它会尝试获取在data中定义的所有属性，用于视图的数据渲染，并且监视data中属性的变化，当data发生变化，所有与之绑定的视图都将重新渲染，这就是响应式系统</li>
</ul>
<h4 id="2-钩子函数">②. 钩子函数</h4>
<ul>
<li>Vue为生命周期中的每个状态都设置了钩子函数（监听函数），每当Vue实例处于不同的生命周期时，对应的函数就会被触发调用</li>
</ul>
<figure data-type="image" tabindex="11"><img src="https://cn.vuejs.org/images/lifecycle.png" alt="Vue 实例生命周期" loading="lazy"></figure>
<ul>
<li><code>beforeCreate()</code>：Vue实例创建之前执行代码</li>
<li><code>created()</code>：Vue实例被创建后执行代码，常用于初始化数据</li>
<li><code>beforeMount</code></li>
<li><code>mounted</code></li>
<li><code>updated</code></li>
<li><code>beforeUpdate</code></li>
<li><code>destroyed</code></li>
<li><code>beforeDestroy</code></li>
</ul>
<blockquote>
<p>钩子函数不要使用箭头函数的方式编写</p>
<p>因为箭头函数并没有 <code>this</code>，<code>this</code> 会作为变量一直向上级词法作用域查找，直至找到为止，经常导致</p>
<p><code>Uncaught TypeError: Cannot read property of undefined</code>  或</p>
<p><code>Uncaught TypeError: this.myMethod is not a function</code>  之类的错误。</p>
</blockquote>
<h3 id="5-插值">5. 插值 <code>{{}}</code></h3>
<ul>
<li>
<p>指令：是指带有<code>v-</code> 前缀的特殊属性，例如 <code>v-model</code></p>
</li>
<li>
<p>插值表达式：<code>{{key}}</code></p>
</li>
<li>
<p>用于替换插值表达式：<code>v-text</code> <code>v-html</code></p>
<ul>
<li><code>v-text</code>：将数据输出到元素内部，如果输出的数据有HTML代码，作为普通文本输出</li>
<li><code>v-html</code>：将数据输出到元素的内部，如果输出的数据有HTML代码，会被渲染到页面上</li>
</ul>
</li>
</ul>
<h3 id="6-双向绑定-v-model">6. 双向绑定 <code>v-model</code></h3>
<ul>
<li>因为是双向绑定，意味着数据的改变会影响到视图的渲染，而视图的改变同样会影响到数据的改变，这就要求视图中的元素具备可修改数据的功能，所以可以双向绑定的元素是固定有限的
<ul>
<li><code>input</code></li>
<li><code>select</code></li>
<li><code>textarea</code></li>
<li><code>checkbox</code></li>
<li><code>radio</code></li>
<li><code>components</code></li>
</ul>
</li>
</ul>
<h3 id="7-事件绑定-v-on">7. 事件绑定 <code>v-on</code></h3>
<ul>
<li>
<p>格式：<code>v-on:click=&quot;num++&quot;</code></p>
</li>
<li>
<p>简写为：<code>@click=&quot;num++&quot;</code></p>
</li>
<li>
<p>实例代码：</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;第一课&lt;/title&gt;
    &lt;script src=&quot;node_modules/vue/dist/vue.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;
        &lt;input type=&quot;text&quot; v-model=&quot;day&quot;/&gt;
        &lt;button v-on:click=&quot;day++&quot;&gt;点我加一&lt;/button&gt;
        &lt;h2&gt;{{name}}学Vue，学了{{day}}天&lt;/h2&gt;
        &lt;button @click=&quot;decrement&quot;&gt;点我减一{{num}}&lt;/button&gt;
    &lt;/div&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        var app = new Vue({
           el:&quot;#app&quot;,
           data:{
               name:&quot;絷缘&quot;,
               day:20,
               num:0
           },
           created() {
               this.num = 100;
           },
           methods:{
               decrement(){
                   this.num--;
               }
           }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
</li>
<li>
<p>事件修饰符</p>
<ul>
<li><code>.stop</code>：阻止事件冒泡</li>
<li><code>.prevent</code>：阻止默认事件发生</li>
<li><code>.capture</code>：使用事件捕获模式</li>
<li><code>.self</code>：只有元素自身触发事件才执行（冒泡或捕获的都不执行）</li>
<li><code>.once</code>：只执行一次</li>
</ul>
</li>
<li>
<p>事件冒泡测试</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;事件冒泡测试&lt;/title&gt;
    &lt;script src=&quot;./node_modules/vue/dist/vue.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;
        &lt;div style=&quot;width: 100px;height: 100px;background-color: #666666;&quot; @click=&quot;print('div被点击')&quot;&gt;
            &lt;button @click.stop=&quot;print('按钮被点击')&quot;&gt;事件冒泡&lt;/button&gt;
            &lt;a href=&quot;https://www.baidu.com&quot; target=&quot;_blank&quot; @click.prevent=&quot;print('a被点击')&quot;&gt;前往百度&lt;/a&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        var app = new Vue({
           el:&quot;#app&quot;,
           data:{
             name:&quot;絷缘&quot;
           },
           methods:{
               print(str){
                   console.log(str);
               }
           }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3 id="8-数组-对象遍历">8. 数组、对象遍历</h3>
<ul>
<li>
<p>指令：<code>v-for</code></p>
</li>
<li>
<p>实例代码：</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;集合数据遍历渲染&lt;/title&gt;
    &lt;script src=&quot;./node_modules/vue/dist/vue.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;
        &lt;table width=&quot;500&quot; cellspacing=&quot;0&quot; cellpadding=&quot;0&quot; border=&quot;1&quot;&gt;
            &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;序号&lt;/th&gt;
                &lt;th&gt;userId&lt;/th&gt;
                &lt;th&gt;userName&lt;/th&gt;
                &lt;th&gt;userAge&lt;/th&gt;
                &lt;th&gt;userGender&lt;/th&gt;
            &lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody&gt;
            &lt;tr v-for=&quot;(user,index) in users&quot;&gt;
                &lt;th&gt;{{index}}&lt;/th&gt;
                &lt;th&gt;{{user.userId}}&lt;/th&gt;
                &lt;th&gt;{{user.userName}}&lt;/th&gt;
                &lt;th&gt;{{user.userAge}}&lt;/th&gt;
                &lt;th&gt;{{user.userGender}}&lt;/th&gt;
            &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/div&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        var app = new Vue({
            el:&quot;#app&quot;,
            data:{
                users:[
                    {&quot;userId&quot;:1,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                    {&quot;userId&quot;:2,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                    {&quot;userId&quot;:3,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                    {&quot;userId&quot;:4,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                    {&quot;userId&quot;:5,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                    {&quot;userId&quot;:6,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                    {&quot;userId&quot;:7,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                    {&quot;userId&quot;:8,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                    {&quot;userId&quot;:9,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                    {&quot;userId&quot;:10,&quot;userName&quot;:&quot;絷缘&quot;,&quot;userAge&quot;:23,&quot;userGender&quot;:&quot;male&quot;},
                ]
            }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<figure data-type="image" tabindex="12"><img src="http://pic.zyblog.xyz/img/typora/20210313121405.png" alt="image-20210313121405486" loading="lazy"></figure>
</li>
</ul>
</li>
<li>
<p>为消除数据被增删时对视图渲染产生的影响，我们需要使用一个特殊的语法 <code>:key=&quot;&quot;</code>，通过key与集合元素中单个元素的唯一属性进行绑定，保证数据的唯一性，从 而使数据增删时，视图渲染不受影响</p>
</li>
<li>
<p><code>:key=&quot;&quot;</code> 是 <code>v-bind:key=&quot;&quot;</code> 的简写</p>
</li>
</ul>
<h3 id="8-指令-v-if-v-show">8. 指令 <code>v-if</code> <code>v-show</code></h3>
<h4 id="1-v-if-v-else-if-v-else">①. <code>v-if</code> <code>v-else-if</code> <code>v-else</code></h4>
<ul>
<li>DOM动态渲染，对元素进行动态添加或删除</li>
</ul>
<h4 id="2-v-show">②. <code>v-show</code></h4>
<ul>
<li>通过元素的css <code>display:none</code> 对元素做显示或隐藏</li>
</ul>
<h3 id="9-指令-v-bind">9. 指令 <code>v-bind</code></h3>
<h2 id="八-springboot">八、SpringBoot</h2>
<h3 id="1-什么是springboot">1. 什么是SpringBoot</h3>
<h4 id="1-概述-2">①. 概述</h4>
<ul>
<li>SpringBoot称为搭建程序的脚手架，或者说是便捷搭建基于Spring工程的脚手架</li>
</ul>
<h4 id="2-作用-2">②. 作用</h4>
<ul>
<li>帮助开发人员快速地构建庞大的Spring项目，并且尽可能地减少一切xml文件的配置，做到开箱即用，让开发人员将注意力放在业务上而不是配置上</li>
</ul>
<h4 id="3-解决的问题">③. 解决的问题</h4>
<ul>
<li>繁杂的配置文件</li>
<li>混乱的依赖管理</li>
</ul>
<h4 id="4-主要特点">④. 主要特点</h4>
<ul>
<li>创建独立的Spring应用，为所有Spring开发者提供一个非常快速地、广泛接受的入门体验</li>
<li>直接嵌入应用服务器，如tomcat、jetty、undertow等，不需要去部署war包</li>
<li>提供固定的启动器依赖去简化组件配置，实现开箱即用</li>
<li>自动地配置Spring和其他有需要的第三方依赖</li>
<li>提供了一些代行项目中常见的非功能性特性，如内嵌服务器、安全、指标、健康检测、外部配置等</li>
<li>绝对没有代码生成，也无需xml配置</li>
</ul>
<h3 id="2-springboot配置文件">2. SpringBoot配置文件</h3>
<h4 id="1-配置文件类型">①. 配置文件类型</h4>
<ul>
<li>properties</li>
<li>yml / yaml</li>
</ul>
<h4 id="2-yaml以数据为核心的配置文件">②. yaml：以数据为核心的配置文件</h4>
<ul>
<li>
<p>基本语法</p>
<ul>
<li>大小写敏感</li>
<li>数据值前必须由空格分隔</li>
<li>使用空格缩进表示层级关系，相同缩进表示同一级</li>
</ul>
</li>
<li>
<p>数据格式</p>
<ul>
<li>
<p>对象</p>
<ul>
<li>
<pre><code class="language-yaml">server:
	port: 8080
</code></pre>
</li>
<li>
<pre><code class="language-yaml">server: {port: 8080}
</code></pre>
</li>
</ul>
</li>
<li>
<p>数组</p>
<ul>
<li>
<pre><code class="language-yaml">language:
	- zh-cn
	- en
	- jp
</code></pre>
</li>
<li>
<pre><code class="language-yaml">language: [zh-cn,en,jp]
</code></pre>
</li>
</ul>
</li>
<li>
<p>纯量</p>
<ul>
<li>
<pre><code class="language-yaml">username: 'zhiyuan\n' #单引号内原样输出
username: &quot;zhiyuan\n&quot; #双引号内可以识别转义字符
</code></pre>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p>参数引用</p>
<ul>
<li>
<p>通过$符号可以引用已经存在于yaml配置文件中的纯量参数</p>
<pre><code class="language-yaml">url: &quot;jdbc:mysql://localhost:3306/test?serverTimeZone=HongKong&quot;

jdbc:
	url: ${url}
</code></pre>
</li>
</ul>
</li>
</ul>
<h4 id="3-springboot内部配置加载顺序">③. SpringBoot内部配置加载顺序</h4>
<ul>
<li>file:<code>./config/</code>：从当前项目路径中的config目录中加载配置文件</li>
<li>file:<code>./</code>：从当前项目的根目录中加载配置文件</li>
<li>classpath:<code>/config/</code>：classpath的config目录中加载配置文件</li>
<li>classpath:<code>/</code>：classpath的根目录中加载配置文件</li>
</ul>
<h3 id="3-springboot入门">3. SpringBoot入门</h3>
<h4 id="1-步骤">①. 步骤</h4>
<ul>
<li>
<p>创建maven项目</p>
</li>
<li>
<p>添加SpringBoot父级依赖</p>
<pre><code class="language-xml">&lt;parent&gt;
    &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;version&gt;2.4.2&lt;/version&gt;
&lt;/parent&gt;
</code></pre>
</li>
<li>
<p>添加SpringBoot启动器依赖</p>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre>
</li>
<li>
<p>设置JDK版本信息</p>
<pre><code class="language-xml">&lt;properties&gt;
    &lt;java.version&gt;1.8&lt;/java.version&gt;
&lt;/properties&gt;
</code></pre>
</li>
<li>
<p>编写启动引导类</p>
<pre><code class="language-java">/**
 * Spring Boot工程都有一个启动引导类，这是工程的入口，并在引导类上添加 @SpringBootApplication 注解
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
</code></pre>
</li>
<li>
<p>编写简单Controller</p>
<pre><code class="language-java">@RestController
public class TestController {

    @GetMapping(&quot;/hello&quot;)
    public String hello(){
        return &quot;Hello!SpringBoot!&quot;;
    }
}
</code></pre>
</li>
<li>
<p>成功访问</p>
<figure data-type="image" tabindex="13"><img src="http://pic.zyblog.xyz/img/typora/20210313144218.png" alt="image-20210313144218537" loading="lazy"></figure>
</li>
</ul>
<h4 id="2-java代码方式配置">②. Java代码方式配置</h4>
<ul>
<li>
<p>Java配置主要靠Java类和一些注解，比较常用的注解有</p>
<ul>
<li><code>@Configuration</code>：声明一个类作为配置类，代替xml文件</li>
<li><code>@Bean</code>：声明在方法上，将方法返回值加入Bean容器，代替bean标签</li>
<li><code>@Value</code>：属性注入</li>
<li><code>@PropertySource</code>：指定外部属性文件</li>
</ul>
</li>
<li>
<p>实现配置数据库连接池</p>
<ul>
<li>导入依赖</li>
</ul>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;com.alibaba&lt;/groupId&gt;
    &lt;artifactId&gt;druid&lt;/artifactId&gt;
    &lt;version&gt;1.2.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;mysql&lt;/groupId&gt;
    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
    &lt;version&gt;8.0.21&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<ul>
<li>创建配置文件</li>
</ul>
<pre><code class="language-properties">jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springbootdb?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456
</code></pre>
<ul>
<li>创建配置类</li>
</ul>
<pre><code class="language-java">@Configuration
@PropertySource(&quot;classpath:jdbc.properties&quot;)
public class JdbcConfig {
    @Value(&quot;${jdbc.driverClassName}&quot;)
    String driverClassName;
    @Value(&quot;${jdbc.url}&quot;)
    String url;
    @Value(&quot;${jdbc.username}&quot;)
    String username;
    @Value(&quot;${jdbc.password}&quot;)
    String password;

    @Bean
    public DataSource getDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(this.driverClassName);
        druidDataSource.setUrl(this.url);
        druidDataSource.setUsername(this.username);
        druidDataSource.setPassword(this.password);
        return druidDataSource;
    }
}
</code></pre>
<ul>
<li>根据类型注入属性</li>
</ul>
<pre><code class="language-java">@RestController
public class TestController {

    @Autowired
    private DataSource ds;

    @GetMapping(&quot;/hello&quot;)
    public String hello(){
        System.out.println(ds);
        return &quot;Hello!SpringBoot!&quot;;
    }
}
</code></pre>
<ul>
<li>控制台打印</li>
</ul>
<pre><code class="language-json">{
	CreateTime:&quot;2021-03-13 15:02:01&quot;,
	ActiveCount:0,
	PoolingCount:0,
	CreateCount:0,
	DestroyCount:0,
	CloseCount:0,
	ConnectCount:0,
	Connections:[
	]
}

</code></pre>
</li>
</ul>
<h4 id="3-springboot属性注入方式">③. SpringBoot属性注入方式</h4>
<ul>
<li>
<p><code>@ConfigurationProperties</code></p>
<ul>
<li>该注解可以将SpringBoot中的配置文件（application.properties、application.yml）中的配置项读取到一个对象中</li>
</ul>
</li>
<li>
<p>步骤</p>
<ul>
<li>创建名为application的properties文件</li>
</ul>
<pre><code class="language-properties">jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springbootdb?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456
</code></pre>
<ul>
<li>创建JdbcProperties配置类</li>
</ul>
<pre><code class="language-java">@ConfigurationProperties(prefix = &quot;jdbc&quot;)
public class JdbcProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
</code></pre>
<ul>
<li>导入依赖</li>
</ul>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-configuration-processor&lt;/artifactId&gt;
    &lt;optional&gt;true&lt;/optional&gt;
&lt;/dependency&gt;
</code></pre>
<ul>
<li>创建JdbcConfig配置类</li>
</ul>
<pre><code class="language-java">@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
    @Bean
    public DataSource getDataSource(JdbcProperties jdbcProperties){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(jdbcProperties.getDriverClassName());
        druidDataSource.setUrl(jdbcProperties.getUrl());
        druidDataSource.setUsername(jdbcProperties.getUsername());
        druidDataSource.setPassword(jdbcProperties.getPassword());
        return druidDataSource;
    }
}
</code></pre>
</li>
<li>
<p>优化</p>
<ul>
<li>移除 <code>JdbcProperties</code> 配置类</li>
<li>直接在 <code>JdbcConfig</code> 的方法上加注解</li>
</ul>
<pre><code class="language-java">@Configuration
public class JdbcConfig {

    @Bean
    @ConfigurationProperties(prefix = &quot;jdbc&quot;)
    public DataSource getDataSource(){
        return new DruidDataSource();
    }
}
</code></pre>
</li>
</ul>
<h4 id="4-多个yml文件配置多个properties文件配置">④. 多个yml文件配置（多个properties文件配置）</h4>
<ul>
<li>
<p>单个yaml文件中的多个yaml配置</p>
<ul>
<li>
<p>单个yaml文件可以使用 <code>---</code> 对多个配置进行分类</p>
<ul>
<li>
<pre><code class="language-yaml">---
# 开发环境配置信息
server:
	port: 8080
spring:
	profiles: dev
---
# 测试环境配置信息
server:
	port: 8080
spring:
	profiles: test
---
# 生产环境配置信息
server:
	port: 8080
spring:
	profiles: pro
</code></pre>
</li>
</ul>
</li>
<li>
<pre><code class="language-yaml"># 激活对应配置信息
spring:
	profiles:
		actice: pro
</code></pre>
</li>
</ul>
</li>
<li>
<p>多个yml文件的配置 / 多个properties文件配置</p>
<ul>
<li>
<p>SpringBoot中允许多个 yml / properties 配置文件，这些配置文件的名称必须为 <code>application-***.yml</code> <code>application-***.properties</code>并且这些配置文件必须要在 <code>application.yml</code>  <code>application.properties</code>中激活之后才可以使用</p>
</li>
<li>
<p>如果properties和yml配置文件同时存在SpringBoot项目中，那么这两种文件都有效，在两个配置文件中如果存在同名的配置项，以properties文件为主</p>
</li>
<li>
<p>激活其他配置文件的方式</p>
<ul>
<li>
<pre><code class="language-yaml"># yaml激活写法
spring:
  profiles:
    active: dev
</code></pre>
</li>
<li>
<pre><code class="language-properties"># properties文件激活写法
spring.profiles.active=pro
</code></pre>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p>以上都是使用profile的配置方式激活对应配置文件，profile的激活方式共有以下几种：</p>
<ul>
<li>配置文件</li>
<li>虚拟机参数 <code>-Dspring.profile.active=pro</code></li>
<li>命令行参数 <code>--spring.profile.active=pro</code>
<ul>
<li><code>java -jar 项目打包后的文件名 --spring.profile.active=pro </code></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4 id="5-lombok应用">⑤. lombok应用</h4>
<blockquote>
<p>lombok是一个插件工具类包，提供了一些注解 <code>@Data</code> <code>@Getter</code> <code>@Setter</code> 等这些注解去简化实体类中的构造方法、get/set等方法的编写</p>
</blockquote>
<ul>
<li>步骤</li>
</ul>
<ol>
<li>在IDEA中安装lombok插件</li>
<li>添加lombok对应的依赖</li>
<li>使用lombok的注解改造实体类</li>
</ol>
<ul>
<li>
<p>注解</p>
<ul>
<li><code>@Data</code>：自动提供getter、setter、hashCode、equals、toString方法</li>
<li><code>@Getter</code>：自动提供getter方法</li>
<li><code>@Setter</code>：自动提供setter方法</li>
<li><code>@Slf4j</code>：自动在bean中提供log变量</li>
</ul>
</li>
<li>
<p>实现</p>
<ul>
<li>导入依赖</li>
</ul>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
    &lt;artifactId&gt;lombok&lt;/artifactId&gt;
    &lt;version&gt;1.18.16&lt;/version&gt;
    &lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre>
<ul>
<li>创建实体类</li>
</ul>
<pre><code class="language-java">@Data
@Slf4j
public class User {
    private int id;
    private String username;
    private String password;
    private Date jointime;
}
</code></pre>
</li>
</ul>
<h4 id="6-修改springmvc端口和静态资源">⑥. 修改SpringMVC端口和静态资源</h4>
<ul>
<li>
<p>修改Tomcat端口</p>
<pre><code class="language-yaml">server:
  port: 80
  servlet:
  	context-path: /hello
</code></pre>
</li>
<li>
<p>访问项目中的静态资源</p>
<ul>
<li><code>classpath:/META-INF/resources/</code></li>
<li><code>classpath:/resources/</code></li>
<li><code>classpath:/static/</code></li>
<li><code>classpath:/public/</code></li>
</ul>
</li>
</ul>
<h4 id="7-springmvc拦截器配置">⑦. SpringMVC拦截器配置</h4>
<ul>
<li>日志记录级别</li>
</ul>
<pre><code class="language-yaml">logging:
  level:
  com.dnc: debug
  org.springframework: info
</code></pre>
<ul>
<li>编写自定义拦截器</li>
</ul>
<pre><code class="language-java">@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug(&quot;MyInterceptor的preHandle方法&quot;);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug(&quot;MyInterceptor的postHandle方法&quot;);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug(&quot;MyInterceptor的afterCompletion方法&quot;);
    }
}
</code></pre>
<ul>
<li>编写拦截器配置类，重写方法添加拦截器功能</li>
</ul>
<pre><code class="language-java">@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Bean
    public MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加拦截器，拦截所有请求
        registry.addInterceptor(myInterceptor()).addPathPatterns(&quot;/*&quot;);
    }
}
</code></pre>
<h4 id="8-事务和连接池">⑧. 事务和连接池</h4>
<ul>
<li>
<p>事务配置</p>
<ul>
<li>添加事务相关依赖，mysql相关依赖</li>
<li>编写业务UserService使用事务注解 <code>@Transactional</code></li>
</ul>
</li>
<li>
<p>数据库连接池 <code>hikari</code> 配置</p>
</li>
<li>
<p>SpringBoot集成的默认数据库连接池，只需要我们配置就好了，据说效率比druid高</p>
</li>
<li>
<p>步骤</p>
<ul>
<li>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre>
</li>
<li>
<p>数据库连接池默认使用hikari，在配置文件中配置如下就可以了</p>
<pre><code class="language-yaml">spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springbootdb?serverTimezone=Asia/Shanghai
    username: root
    password: 123456
</code></pre>
</li>
</ul>
</li>
</ul>
<h4 id="9-springboot整合mybatis">⑨. SpringBoot整合MyBatis</h4>
<ul>
<li>
<p>添加启动器依赖</p>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;
    &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;
    &lt;version&gt;2.1.3&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
</li>
<li>
<p>配置MyBatis：实体类别名包，日志，映射文件等</p>
<pre><code class="language-yaml">mybatis:
  #配置实体类别名包路径
  type-aliases-package: com.dnc.entity
  #配置映射文件路径
  mapper-locations: classpath:mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
</code></pre>
</li>
<li>
<p>配置MapperScan</p>
<pre><code class="language-java">@SpringBootApplication
@MapperScan(&quot;com.dnc.mapper&quot;)
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
</code></pre>
</li>
</ul>
<h4 id="10-springboot通用mapper">⑩. SpringBoot通用Mapper</h4>
<ul>
<li>
<p>添加启动器依赖</p>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;tk.mybatis&lt;/groupId&gt;
    &lt;artifactId&gt;mapper-spring-boot-starter&lt;/artifactId&gt;
    &lt;version&gt;2.1.5&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
</li>
<li>
<p>改造UserMapper继承 Mapper <User></p>
</li>
<li>
<p>修改启动引导类Application中的Mapper扫描注解</p>
</li>
<li>
<p>修改User实体类添加JPA注解</p>
</li>
<li>
<p>改造UserService实现业务功能</p>
</li>
</ul>
<blockquote>
<p>此处注意一个问题，实体类中所有成员属性的类型必须为引用类型，基本类型会导致SQL无法执行</p>
</blockquote>
<h3 id="3-springboot整合测试">3. SpringBoot整合测试</h3>
<blockquote>
<p>http://localhost/user/1</p>
<pre><code class="language-json">{
  &quot;id&quot;: 1,
  &quot;username&quot;: &quot;絷缘&quot;,
  &quot;password&quot;: &quot;123456&quot;,
  &quot;jointime&quot;: &quot;2021-03-13 23:31:23&quot;
}
</code></pre>
</blockquote>
<h3 id="4-springboot整合junit">4. SpringBoot整合Junit</h3>
<h4 id="1-添加启动器依赖-spring-boot-starter-test">①. 添加启动器依赖 <code>spring-boot-starter-test</code></h4>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre>
<h4 id="2-编写测试代码">②. 编写测试代码</h4>
<pre><code class="language-java">@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class UserServiceTest {

    @Autowired
    private UserService userService;
    @Test
    public void queryById() {
        User user = userService.queryById(1);
        System.out.println(user);
    }
}

//输出结果
User(id=1, username=絷缘, password=123456, jointime=Sat Mar 13 23:31:23 CST 2021)
</code></pre>
<h3 id="5-springboot整合redis">5. SpringBoot整合Redis</h3>
<h4 id="1-添加启动器依赖-spring-boot-starter-data-redis">①. 添加启动器依赖 <code>spring-boot-starter-data-redis</code></h4>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre>
<h4 id="2-配置applicationyml中修改redis的连接参数">②. 配置application.yml中修改redis的连接参数</h4>
<pre><code class="language-yaml">spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springbootdb?serverTimezone=Asia/Shanghai
    username: root
    password: 123456
  redis:
    host: localhost
    port: 6379
</code></pre>
<h4 id="3-编写测试类引用redistemplate操作redis中的五种数据类型">③. 编写测试类引用RedisTemplate操作redis中的五种数据类型</h4>
<ul>
<li>string</li>
<li>hash</li>
<li>list</li>
<li>set</li>
<li>sorted set</li>
</ul>
<pre><code class="language-java">@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void test(){
        //操作string类型
        redisTemplate.opsForValue().set(&quot;username&quot;,&quot;絷缘&quot;);
        redisTemplate.boundValueOps(&quot;name&quot;).set(&quot;絷缘&quot;);
        System.out.println(&quot;username=&quot; + redisTemplate.opsForValue().get(&quot;username&quot;));
        System.out.println(&quot;name=&quot; + redisTemplate.opsForValue().get(&quot;name&quot;));
        //操作hash散列
        redisTemplate.boundHashOps(&quot;user&quot;).put(&quot;username&quot;,&quot;zhiyuan&quot;);
        redisTemplate.boundHashOps(&quot;user&quot;).put(&quot;nickname&quot;,&quot;絷缘&quot;);
        redisTemplate.boundHashOps(&quot;user&quot;).put(&quot;password&quot;,&quot;123456&quot;);
        System.out.println(&quot;username=&quot; + redisTemplate.opsForHash().get(&quot;user&quot;,&quot;username&quot;));
        System.out.println(&quot;nickname=&quot; + redisTemplate.opsForHash().get(&quot;user&quot;,&quot;nickname&quot;));
        System.out.println(&quot;password=&quot; + redisTemplate.opsForHash().get(&quot;user&quot;,&quot;password&quot;));
        Set userkeys = redisTemplate.boundHashOps(&quot;user&quot;).keys();
        System.out.println(&quot;userkeys=&quot; + userkeys);
        List uservalues = redisTemplate.boundHashOps(&quot;user&quot;).values();
        System.out.println(&quot;uservalues=&quot; + uservalues);
        //操作list集合
        redisTemplate.boundListOps(&quot;person&quot;).leftPush(&quot;personA&quot;);
        redisTemplate.boundListOps(&quot;person&quot;).leftPush(&quot;personB&quot;);
        redisTemplate.boundListOps(&quot;person&quot;).leftPush(&quot;personC&quot;);
        List person = redisTemplate.boundListOps(&quot;person&quot;).range(0, -1);
        System.out.println(&quot;person=&quot; + person);
        //操作set集合
        redisTemplate.boundSetOps(&quot;animals&quot;).add(&quot;dog&quot;,&quot;cat&quot;,&quot;pig&quot;,&quot;horse&quot;);
        Set animals = redisTemplate.boundSetOps(&quot;animals&quot;).members();
        System.out.println(&quot;animals=&quot; + animals);
        //操作sortedset集合
        redisTemplate.boundZSetOps(&quot;student&quot;).add(&quot;studentA&quot;,22);
        redisTemplate.boundZSetOps(&quot;student&quot;).add(&quot;studentB&quot;,25);
        redisTemplate.boundZSetOps(&quot;student&quot;).add(&quot;studentC&quot;,21);
        redisTemplate.boundZSetOps(&quot;student&quot;).add(&quot;studentD&quot;,26);
        Set student = redisTemplate.boundZSetOps(&quot;student&quot;).range(0, -1);
        System.out.println(&quot;student=&quot; + student);
    }
}
//输出结果
username=絷缘
name=絷缘
username=zhiyuan
nickname=絷缘
password=123456
userkeys=[username, nickname, password]
uservalues=[zhiyuan, 絷缘, 123456]
person=[personC, personB, personA, personC, personB, personA, personC, personB, personA]
animals=[dog, pig, cat, horse]
student=[studentC, studentA, studentB, studentD]
</code></pre>
<h3 id="6-springboot项目部署">6. SpringBoot项目部署</h3>
<blockquote>
<p>目标：将SpringBoot项目使用maven指令打成jar包并运行测试</p>
</blockquote>
<ol>
<li>将项目中的资源、配置、依赖包打到一个jar包中：使用 <code>maven</code>  的 <code>package</code> 命令</li>
<li>部署jar包：<code>java -jar 包名</code></li>
</ol>
<pre><code class="language-xml">&lt;build&gt;
    &lt;resources&gt;
        &lt;resource&gt;
            &lt;directory&gt;src/main/resources&lt;/directory&gt;
            &lt;includes&gt;
                &lt;include&gt;**/*.xml&lt;/include&gt;
            &lt;/includes&gt;
        &lt;/resource&gt;
    &lt;/resources&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
            &lt;configuration&gt;
                &lt;mainClass&gt;com.xzy.youpin.Application&lt;/mainClass&gt;
            &lt;/configuration&gt;
            &lt;executions&gt;
                &lt;execution&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;repackage&lt;/goal&gt;
                    &lt;/goals&gt;
                &lt;/execution&gt;
            &lt;/executions&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;
</code></pre>
<ol start="3">
<li>安装插件 <code>JBLSpringBootAppGen</code>，可以自动创建 <code>Application.java</code> 和 <code>application.yml</code></li>
</ol>
<h2 id="九-thymeleaf">九、thymeleaf</h2>
<h2 id="十-springsecurity">十、 SpringSecurity</h2>
<blockquote>
<p>RBAC（Role-Based-Access-Control）：基于角色的权限管理</p>
<p>认证 + 授权</p>
</blockquote>
<h3 id="1-步骤-2">1. 步骤</h3>
<h4 id="1-httpbasic模式的认证">①. HttpBasic模式的认证</h4>
<h4 id="2-formlogin模式的认证">②. FormLogin模式的认证</h4>
<ul>
<li>编写login.html文件</li>
<li>创建配置类继承 <code>WebSecurityConfigurerAdapter</code></li>
<li>重写 <code>configure(HttpSecurity http)</code> 配置登录验证逻辑</li>
<li>重写 <code>configure(AuthenticationManagerBuilder auth)</code> 实现内存身份验证</li>
<li>运行验证</li>
</ul>
<h4 id="3-前后端分离架构的认证">③. 前后端分离架构的认证</h4>
<h2 id="十一-mybatis-plus">十一、MyBatis-Plus</h2>
<h3 id="1-导包">1. 导包</h3>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;com.baomidou&lt;/groupId&gt;
    &lt;artifactId&gt;mybatis-plus&lt;/artifactId&gt;
    &lt;version&gt;mybatis-plus-latest-version&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/com.alibaba/druid --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;com.alibaba&lt;/groupId&gt;
    &lt;artifactId&gt;druid&lt;/artifactId&gt;
    &lt;version&gt;1.2.6&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;mysql&lt;/groupId&gt;
    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
    &lt;version&gt;8.0.21&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
    &lt;artifactId&gt;lombok&lt;/artifactId&gt;
    &lt;version&gt;1.18.12&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt;
    &lt;version&gt;1.7.25&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<h3 id="2-配置log4j">2. 配置log4j</h3>
<pre><code class="language-properties">log4j.rootLogger=DEBUG,A1

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.Layout.ConversionPattern=[%t] [%c]-[%p] %m%n
</code></pre>
<h3 id="3-springboot整合mybatis-plus">3. SpringBoot整合Mybatis-Plus</h3>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;com.baomidou&lt;/groupId&gt;
    &lt;artifactId&gt;mybatis-plus-boot-starter&lt;/artifactId&gt;
    &lt;version&gt;Latest Version&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<blockquote>
<p>queryWrapper.lt（）——小于<br>
queryWrapper.le（）——小于等于<br>
queryWrapper.gt（）——大于<br>
queryWrapper.ge（）——大于等于<br>
queryWrapper.eq（）——等于<br>
queryWrapper.ne（）——不等于<br>
queryWrapper.betweeen（“age”,10,20）——age在值10到20之间<br>
queryWrapper.notBetweeen（“age”,10,20）——age不在值10到20之间<br>
queryWrapper.like（“属性”,“值”）——模糊查询匹配值‘%值%’<br>
queryWrapper.notLike（“属性”,“值”）——模糊查询不匹配值‘%值%’<br>
queryWrapper.likeLeft（“属性”,“值”）——模糊查询匹配最后一位值‘%值’<br>
queryWrapper.likeRight（“属性”,“值”）——模糊查询匹配第一位值‘值%’<br>
queryWrapper.isNull（）——值为空或null<br>
queryWrapper.isNotNull（）——值不为空或null<br>
queryWrapper.in（“属性”，条件，条件 ）——符合多个条件的值<br>
queryWrapper.notIn(“属性”，条件，条件 )——不符合多个条件的值<br>
queryWrapper.or（）——或者<br>
queryWrapper.and（）——和<br>
queryWrapper.orderByAsc(“属性”)——根据属性升序排序<br>
queryWrapper.orderByDesc(“属性”)——根据属性降序排序<br>
queryWrapper.inSql(“sql语句”)——符合sql语句的值<br>
queryWrapper.notSql(“sql语句”)——不符合SQL语句的值<br>
queryWrapper.esists（“SQL语句”）——查询符合SQL语句的值<br>
queryWrapper.notEsists（“SQL语句”）——查询不符合SQL语句的值</p>
</blockquote>
<blockquote>
<p>原文作者：絷缘<br>
作者邮箱：zhiyuanworkemail@163.com<br>
原文地址：<a href="https://zhiyuandnc.github.io/pILxU31oU/">https://zhiyuandnc.github.io/pILxU31oU/</a><br>
版权声明：本文为博主原创文章，转载请注明原文链接作者信息</p>
</blockquote>

                </div>
            </article>
        </div>

        
            <div class="next-post">
                <div class="next gt-c-content-color-first">下一篇</div>
                <a href="https://zydnc.gitee.io/3pOEFSCc4/" class="post-title gt-a-link">
                    JavaSE学习
                </a>
            </div>
        

        

        

        

        <div class="site-footer gt-c-content-color-first">
    <div class="slogan gt-c-content-color-first">事实不以人的意志为转移</div>
    <div class="social-container">
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-github gt-c-content-color-first"></i>
                </a>
            
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-telegram gt-c-content-color-first"></i>
                </a>
            
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-qq gt-c-content-color-first"></i>
                </a>
            
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-bilibili gt-c-content-color-first"></i>
                </a>
            
        
            
        
            
        
            
        
            
        
            
        
            
        
            
        
            
        
            
        
    </div>
    <div class="footer-info">
        Copyright&ensp;&copy;&ensp;絷缘的博客<br/><a href="https://beian.miit.gov.cn/" target="_blank">晋ICP备20001723号-1</a>
    </div>
    <div>
        Theme by <a href="https://imhanjie.com/" target="_blank">imhanjie</a>, Powered by <a
                href="https://github.com/getgridea/gridea" target="_blank">Gridea | <a href="https://zydnc.gitee.io/atom.xml" target="_blank">RSS</a></a>
    </div>
</div>

<script>
  hljs.initHighlightingOnLoad()
</script>

    </div>
</div>
</body>
</html>
